Avoiding warnings about truncating my C ++ compiler when initializing signed values

I would like to initialize the short value with a hexadecimal value, but my compiler gives me truncation warnings. It is clear that I am trying to set short to a positive value.

 short my_value = 0xF00D; // Compiler sees "my_value = 61453" 

How would you avoid this warning? I could use a negative value,

 short my_value = -4083; // In 2 complement this is 0xF00D 

but in my code it is much clearer to use hex.

0
c ++ initialization warnings truncation
source share
2 answers

Insert a constant.

short my_value = (short)0xF00D;

EDIT: The original explanation made sense in my head, but further thinking was wrong. However, this should suppress the warning and give you what you expect.

+3
source share

You assign an int value that cannot correspond to a short one, therefore a warning. You can disable the compiler using c-type cast, but this is usually bad practice.

It’s better not to do this and assign a negative value. Or, if the value of the hex value makes sense, switch to unsigned short.

0
source share

All Articles