Avoiding truncation warnings from my C++ compiler when initializing signed values

假装没事ソ 提交于 2019-12-12 03:07:25

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!