In the C language, with this code snippet:
uint16_t a = 243;
uint16_t b = 65535;
uint16_t max = 65535;
if ((a + b) > max)
{
printf("Out of range!");
}
else
{
printf("Within range.");
}
The result will be "Out of range!". What type conversion rules apply in this case? Can someone point me to a documented source?
Thanks!
From the C Standard (6.5.6 Additive operators)
and (6.5.8 Relational operators)
and at last (6.3.1.8 Usual arithmetic conversions)
and (6.3.1.1 Boolean, characters, and integers)
So in the condition of the if statement
all operands are converted to the type
int
according to the integer promotions. And an object of the typeint
is able to store the value of the integer expressiona + b
where each operand is in turn converted to the typeint
.In fact the above if statement you may imagine the following way
or like
depending on whether the type
int
orunsigned int
can store the values of the typeuint16_t
.An overflow can occur if for example the size of the type
int
orunsigned int
is the same as the size of the typeuint16_t
.