问题
I would like to initialize a short
to a hexadecimal value, but my compiler gives me truncation warnings. Clearly 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.
回答1:
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.
回答2:
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.
来源:https://stackoverflow.com/questions/4219160/avoiding-truncation-warnings-from-my-c-compiler-when-initializing-signed-value