Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do integer promotions always happen when evaluating an expression? [duplicate]

Possible Duplicate:
C integer overflow behaviour when assigning to larger-width integers

I haven't found a clear answer on this in my googling. Say you have two expressions:

int16_t a16 = 100;
int16_t b16 = 2000;
int16_t result16 = (a16 * b16) / a16;

int8_t a8 = 100;
int8_t b8 = 20;
int8_t result8 = (a8* b8) / a8;

When evaluation the expressions (a16 * b16) / a16 and (a8 * b8) / a8, are they always promoted to int during the evaluation and then the final result is converted back to the desired type (int16_t or int8_t) just before the assignment, or is this integer promotion entirely optional? Is integer promotion while evaluating an integer expression always done, or is it just simply allowed?

If it's always done, then I can expect the two operations to not overflow (assuming int is 32-bits). If it's only allowed to be done (and not required), then the operations may overflow. I'd like to know the behavior better.

like image 320
Cornstalks Avatar asked Oct 09 '12 20:10

Cornstalks


People also ask

What is integer promotion?

Integer promotion is the implicit conversion of a value of any integer type with rank less or equal to rank of int or of a bit field of type _Bool, int, signed int, unsigned int, to the value of type int or unsigned int.

What is a promotion in Java?

Type Promotion in ExpressionsJava automatically promotes each byte, short, or char operand to int when evaluating an expression. If one operand is long, float or double the whole expression is promoted to long, float, or double respectively.


1 Answers

int16_t result16 = (a16 * b16) / a16;
int8_t result8 = (a8* b8) / a8;

These declarations are the same as:

int16_t result16 = (int16_t) ((int) a16 * (int) b16) / (int) a16);
int8_t result8 = (int8_t) ((int) a8 * (int) b8) / (int) a8);

The integer promotions are required by a conforming implementation. Some embedded compilers by default do not perform integer promotions to enhance code density (example: MPLAB C18 compiler) but these compilers usually also have an ANSI mode to be conforming.

Now for C the behavior is described in terms of an abstract machine in which the issues of optimization are irrelevant. If the compiler can achieve the same observable behavior for the program without performing an integer promotion, it is free not to do it.

Assuming your int is 32-bit, you are right, this expression: (a16 * b16) / a16 cannot overflow.

like image 128
ouah Avatar answered Oct 20 '22 16:10

ouah