当有符号值分配给无符号整数时,为什么编译器没有给出错误? - C++
我知道unsigned int不能保存负值。 但以下代码编译时没有任何错误/警告。
unsigned int a = -10;
当我打印变量 a 时,我打印了错误的值。 如果无符号变量不能保存有符号值,为什么编译器允许它们编译而不给出任何错误/警告?
有什么想法吗?
编辑
编译器:VC++编译器
解决方案
需要使用警告级别4。
I know unsigned int can't hold negative values. But the following code compiles without any errors/warnings.
unsigned int a = -10;
When I print the variable a, I get a wrong value printed. If unsigned variables can't hold signed values, why do compilers allow them to compile without giving any error/warning?
Any thoughts?
Edit
Compiler : VC++ compiler
Solution
Need to use the warning level 4.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
微软视觉C++:
警告级别为 4。G
++
给我警告:
没有任何 -W 指令。
海湾合作委员会
你必须使用:
这将给出警告:
请注意,-Wall 不会启用此警告。
也许您只需要调高警告级别即可。
Microsoft Visual C++:
On warning level 4.
G++
Gives me the warning:
Without any -W directives.
GCC
You must use:
Which will give the warning:
Note that -Wall will not enable this warning.
Maybe you just need to turn your warning levels up.
将
signed int
转换为unsigned int
在 C 标准中称为“普通算术转换”,因此这不是错误。默认情况下,编译器通常不会对此发出警告,因为它在代码中非常常见,因此通常会发出太多“误报”警告。 有大量代码使用有符号 int 值来处理本质上无符号的内容(例如计算缓冲区大小)。 在表达式中混合有符号和无符号值也很常见。
这并不是说这些静默转换不会导致错误。 因此,为新代码启用警告可能不是一个坏主意,这样它从一开始就是“干净的”。 但是,我认为您可能会发现处理现有代码发出的警告相当困难。
Converting a
signed int
to anunsigned int
is something known in the C standard as a "Usual arithmetic conversion", so it's not an error.The reason compilers often don't issue a warning on this by default is because it's so commonly done in code there would be far too many 'false positive' warnings issued in general. There is an awful lot of code out there that works with
signed int
values to deal with things that are inherently unsigned (calculating buffer sizes for example). It's also very common to mix signed and unsigned values in expressions.That's not to say that these silent conversions aren't responsible for bugs. So, it might not be a bad idea to enable the warning for new code so it's 'clean' from the start. However, I think you'd probably find it rather overwhelming to deal with the warnings issued by existing code.
-10 被解析为整数值,并且允许将 int 分配给 unsigned int。 要知道你做错了什么,编译器必须检查你的整数(-10)是负数还是正数。 由于它不仅仅是类型检查,我猜它已因性能问题而被禁用。
-10 is parsed as an integer value, and assigning int to unsigned int is allowed. To know you are doing something wrong the compiler has to check whether your integer (-10) is negative or positive. As it is more than a type check, I guess it has been disabled for performance issues.
我正在使用 g++ 4.9.2 并且需要使用 -Wsign-conversion 来显示此警告。
I am using g++ 4.9.2 and need to use -Wsign-conversion to make this warning appear.
对于 gcc 编译器,您可以添加
这将产生以下警告
For gcc compiler you can add
And this will produce the following warning