Tuesday 15 April 2014

What happens when a integer overflow occurs in a C expression? -



What happens when a integer overflow occurs in a C expression? -

i have next c code:

uint8_t firstvalue = 111; uint8_t secondvalue = 145; uint16_t temp = firstvalue + secondvalue; if (temp > 0xff) { homecoming true; } homecoming false;

this alternative implementation:

uint8_t firstvalue = 111; uint8_t secondvalue = 145; if (firstvalue + secondvalue > 0xff) { homecoming true; } homecoming false;

the first illustration obvious, uint16_t type big plenty contain result. when tried sec illustration clang compiler on os/x, correctly returned true. happens there? there sort of temporary, bigger type contain result?

the operands of + promoted larger types, can see going draft c99 standard section 6.5.6 additive operators says:

if both operands have arithmetic type, usual arithmetic conversions performed on them.

and if go 6.3.1.8 usual arithmetic conversions says:

otherwise, integer promotions performed on both operands.

and go 6.3.1.1 boolean, characters, , integers says (emphasis mine):

if int can represent values of original type, value converted int; otherwise, converted unsigned int. these called integer promotions.48) other types unchanged integer promotions.

so both operands of + in case promoted type int operation, there no overflow.

note, why must short converted int before arithmetic operations in c , c++? explains rationale promotions.

c integer-overflow integer-promotion

No comments:

Post a Comment