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);
}
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.
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.
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.
The integer promotions are issued from two different sources in your program:
-
operator1)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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With