I have seen a similar question but mine is specifically referring to the augmented assignment operators such as +=, -=, etc. How exactly do the those operators work when I have the following?
extern signed s;
extern unsigned u;
s += u;
Will this be equivalent to this?
s = (signed)((unsigned)s+u);
More specifically would this invoke undefined behavior due to signed integer overflow?
signed s = INT_MAX;
unsigned u = 1;
s += u;
I am aware that when using the normal arithmetic operators, the unsigned type usually dominates. However, I am not sure if this holds true for the augmented assignment operators.
This:
Is the same as this:
As per section 6.5.16.2p3 of the C standard:
So first
s + uis evaluated. This causessto be converted to typeunsignedas per the usual arithmetic conversions, and the result is unsigned. Then this result is assigned back toswhich undergoes a conversion fromunsignedtosigned.So in this particular case:
The value of
sis converted tounsignedand 1 is added to it, resulting in an unsigned value ofINT_MAX + 1. This value is then converted tosigned, which undergoes an implementation defined conversion due to the value being out of range as per section 6.3.1.3p3:So the above does not have undefined behavior, but it does have implementation defined behavior.