简体   繁体   中英

Warning when type casting a constant to short int in C

I get the warning like this warning "C4310: cast truncates constant value". associated code is

short a = 100;
if( a == (short)0x8000 ) ;// Warning is got here.

Whats the way to remove the warning without making 0x8000 as constant or variable value and without type casting a?

if i modify the condition line to

if( a == (short)-32768 ) ;// No warning seen

Why is this?

Thank you.

The warning is telling you something important.

Assuming a short is 16 bit, valid values are -32768 to 32767. The value 0x8000 (32768) falls outside the range of a short .

Using -32768 works because it fits within the range of a short , and in fact a cast is not needed in this case.

You pretty much have two options:

  1. Write the constant with the value you want it to have after conversion so that the cast can be omitted:

     if( a == -0x8000 ) 

    or,

  2. Disable the warning, as it's specifically preventing you from doing what you want to do: using casts as operators that change values. (A cast that's value-preserving is usually useless, except possibly controlling the type the surrounding expression is evaluated in.)

The key problem that the warning is trying to express to you is that in your C implementation, type short cannot represent the value 0x8000 . Such implementations are not at all unusual, for it is common that short has a 16-bit representation, of which one is a sign bit. The cast has implementation-defined behavior, and very likely not the behavior you expect.

Moreover, without the cast, the equality comparison will always evaluate to false, because, again, short cannot represent the given value, therefore no possible value of a is equal to that value.

You want to use a different type for a . If you use a type that can represent 0x8000 ( unsigned short and signed and unsigned int will all satisfy that criterion) then you will not need to cast. There may be other considerations relevant to which type you should choose, but you haven't presented any.

I think you should use unsigned short so you can use all the bits as you don't care about signs:

unsigned short a = 100;
if( a == 0x8000 ) 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM