Ravi
Ravi

Reputation: 69

Integer promotion in C program

I have written a simple C program and wanted to know if integer promotion is happening in it.

Please explain how integer promotion happens and how to avoid it?

/* start of main */

unsigned short int res;
unsigned short int bsp;
signed short int analog;

bsp = 2215;
analog = 2213;
if((signed short int)(bsp - analog) > 0){
    res = bsp - analog;
    printf("%d", res);
}
else{
    res = analog - bsp;
    printf("%d", res);
}

Upvotes: 5

Views: 527

Answers (2)

Grzegorz Szpetkowski
Grzegorz Szpetkowski

Reputation: 37914

The integer promotions are issued from two different sources in your program:

  • usual arithmetic conversions (because of binary - operator1)
  • default argument promotions (because of printf variadic function)

In both cases, either argument of type signed short int is promoted to int, assuming, that int range can hold every number that former type can hold. Normally, it happens this way as short and int are 16-bit and 32-bit wide respectively.


1) As a well as of > operator (as mentioned in chux's comment below).

Upvotes: 2

Bathsheba
Bathsheba

Reputation: 234685

I'm going to restrict this answer to an int being 32 bit, and short being 16 bit.

Then bsp - analog is an expression of type int.

The behaviour on casting this to a short is undefined if bsp - analog cannot be represented in a short. So write code like (signed short int)(bsp - analog) with caution.

There's an implicit promotion of res to an int in your printf call.

Finally, the best way to avoid unwanted promotions is to work with the same type throughout. Consider using an int or a long in your case.

Upvotes: 2

Related Questions