I have a bit of C code, which goes exactly like this:
short int fun16(void){
short int a = 2;
short int b = 2;
return a+b;
}
When I try to compile it with GCC, I get the warning:
warning: conversion to 'short int' from 'int' may alter its value [-Wconversion]
return a+b;
^
Though there is no visible conversion. Both operands are short and even the returning value is short as well. So, what's the catch?
GCC will only perform these implicit upscaling to int on operations which generate temporaries:
will not generate temporaries.
will.
The following code:
Will give the following output in either release or debug modes: 2 4 4 4 2 4 2
Indicating that while some things may suppress the warning, they don't actually stop the compiler upscaling to int. So to lose the warning, stop the generation of temporaries.
When you do arithmetic computations, the operands are subject to "the usual arithmetic conversions" (a superset of the "integer promotions" quoted in Acme's answer—he beat me to this but I'll go ahead and post anyway :-) ). These widen
short int
to plainint
, so:computes the same result as:
The
return
statement must then narrow thisint
to ashort int
, and this is where gcc produces the warning.If an int can represent all values of the original type, the value is converted to an int; otherwise, it is converted to an unsigned int. These are called the integer promotions. All other types are unchanged by the integer promotions.
Refer the following post: Why must a short be converted to an int before arithmetic operations in C and C++?
Quoting the standard (§6.3.1.1 ¶2):
The
-Wconversion
flag warns about:From The C Programming Language section 2.7 Type Conversion
long double
, convert the other tolong double
.double
, convert the other todouble
.float
, convert the other tofloat
.char
andshort
toint
.long
, convert the other tolong
.When both operands are
short
, they are implicitly promoted toint
in arithmetic operations.