Question

I'm working with GCC v4.4.5 and I've notived a default integer promotion scheme I didn't expected.

To activate enough warnings to prevent implicit bugs I activated the option -Wconversion and since then I've notice that when I perform the code below, the warning "conversion to ‘short int’ from ‘int’ may alter its value" is present.

signed short sA, sB=1, sC=2;
sA = sB + sC;

This means that "sB + sC" is promoted to int and then assigned to sA which is signed short. To fix this warning I have to cast it like this.

signed short sA, sB=1, sC=2;
sA = ( signed short )( sB + sC );

This warning is also present with the code below.

signed short sA=2;
sA += 5;

And can be fixed by removing the operator += by this...

sA = ( signed short )( sA + 1 );

which is a bit annoying cause I can't use the operators +=, -=.

I expected GCC to select the right integer promotion according to the operands. I mean, sA=sB+sC and sA+=5 should not be promoted to int as they all are signed short.

I understand that promoting to int by default prevents overflow bugs but it's a bit annoying cause I have to cast most of my code or change my variables to int.

Is there a GCC option I could use to present this integer promotion scheme ?

Thanks for your help.

Was it helpful?

Solution

This isn't gcc, this is standard C semantics.

Per 6.3.1.1:2, an object or expression with an integer type whose integer conversion rank is less than or equal to the rank of int and unsigned int is converted to int or unsigned int depending on the signedness of the type, prior to participating in arithmetic expressions.

The reason C behaves this way is to allow for platforms where ALU operations on sub-int types are less efficient than those on full int types. You should perform all your arithmetic on int values, and convert back to short only for storage.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top