Reputation: 131
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.
Upvotes: 1
Views: 2499
Reputation: 25286
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 )
Upvotes: 0
Reputation: 223872
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.
Upvotes: 3
Reputation: 180201
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.
Upvotes: 1
Reputation: 215259
You pretty much have two options:
Write the constant with the value you want it to have after conversion so that the cast can be omitted:
if( a == -0x8000 )
or,
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.)
Upvotes: 0