Avoiding truncation warnings from my C++ compiler when initializing signed values
I would like to initialize a short
to a hexadecimal value, but my compiler gives me truncation warnings. C开发者_如何转开发learly it thinks I am trying to set the short
to a positive value.
short my_value = 0xF00D; // Compiler sees "my_value = 61453"
How would you avoid this warning? I could just use a negative value,
short my_value = -4083; // In 2's complement this is 0xF00D
but in my code it is much more understandable to use hexadecimal.
Cast the constant.
short my_value = (short)0xF00D;
EDIT: Initial explanation made sense in my head, but on further reflection was kind of wrong. Still, this should suppress the warning and give you what you expect.
You are assigning an int value that can not fit short, hence the warning. You could silent the compiler by using a c-type cast, but it is usually a bad practice.
A better way is not to do that, and to assign a negative value. Or, if the hexadecimal value makes more sense, to switch to unsigned short.
精彩评论