Edit: Changed the value for USHRT_MAX
as it was not conformant as shown by comments.
Imagine you have a fancy compiler where its integer type limits, as defined in limits.h are:
#define INT_MAX 2147483647 /* Typical 32-bit system value */
#define USHRT_MAX 2147483647 /* ***Edited***, original question had 2000000000 */
And in my application I have the following code:
unsigned short a = 1500000000;
unsigned short b = 1500000000;
unsigned short c;
c = a + b;
As far as I know, what will happen in the last instruction will be:
- Integral promotion on
a
. Asint
can take all values ofunsigned short
,a
gets promoted toint
. - For the same reasons,
b
gets promoted toint
. - Addition happens on
int
types. - The result is not representable in
int
. Undefined Behavior due to paragraph 6.5/5.
Is my reasoning correct? Does this really invoke undefined behavior, or where did I go wrong? Note that my code only works with unsigned types, and a result applying the modulus for unsigned integers could be expected due to legal overflow on unsigned types.
If the answer to the previous question is "yes, undefined behavior", this happened for a legal conformant compiler. So, can you say that the application code I posted is incorrect? Do all non-explicitly-casted small unsigned integer additions potentially invoke undefined behavior?