Why are integer types promoted during addition in C? -
so had field issue, , after days of debugging, narrowed down problem particular bit of code, processing in while loop wasn't happening :
// heavily redacted code // numbera , numberb both of uint16_t // important stuff happens in while loop while ( numbera + 1 == numberb ) { // processing }
this had run fine, until hit uint16 limit of 65535. bunch of print statements later, discovered numbera + 1
had value of 65536
, while numberb
wrapped 0
. failed check , no processing done.
this got me curious, put quick c program (compiled gcc 4.9.2) check this:
#include <stdio.h> #include <stdint.h> int main() { uint16_t numbera, numberb; numbera = 65535; numberb = numbera + 1; uint32_t numberc, numberd; numberc = 4294967295; numberd = numberc + 1; printf("numbera = %d\n", numbera + 1); printf("numberb = %d\n", numberb); printf("numberc = %d\n", numberc + 1); printf("numberd = %d\n", numberd); return 0; }
and result :
numbera = 65536 numberb = 0 numberc = 0 numberd = 0
so appears result of numbera + 1
promoted uint32_t. intended c language ? or compiler / hardware oddity?
so appears result of
numbera + 1
promoteduint32_t
the operands of addition promoted int
before addition took place, , result of addition of same type effective operands (int
).
indeed, if int
32-bit wide on compilation platform (meaning type represents uint16_t
has lower “conversion rank” int
), numbera + 1
computed int
addition between 1
, promoted numbera
part of integer promotion rules, 6.3.1.1:2 in c11 standard:
the following may used in expression wherever int or unsigned int may used: […] object or expression integer type (other int or unsigned int) integer conversion rank less or equal rank of int , unsigned int.
[…]
if int can represent values of original type […], value converted int
in case, unsigned short
in likelihood uint16_t
defined on platform, has values representable elements of int
, unsigned short
value numbera
gets promoted int
when occurs in arithmetic operation.