Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Integer promotion in C program

Tags:

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);
}
like image 388
Ravi Avatar asked Jul 07 '16 10:07

Ravi


People also ask

What is integer promotion in C?

There are some data types which take less number of bytes than integer datatype such as char, short etc. If any operations are performed on them, they automatically get promoted to int. This is known as integer promotions.

What is type promotion in C?

Introduction. Type promotion in C is a method to convert any variable from one datatype to another. C allows variables of different datatypes to be present in a single expression. There are different types of type conversions available in C. They are Implicit type conversion and Explicit type conversion.


2 Answers

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.

like image 134
Bathsheba Avatar answered Oct 05 '22 23:10

Bathsheba


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).

like image 24
Grzegorz Szpetkowski Avatar answered Oct 05 '22 21:10

Grzegorz Szpetkowski