为什么编译器在带符号值分配给无符号整数时不会产生错误? - C ++ [英] Why compiler is not giving error when signed value is assigned to unsigned integer? - C++
问题描述
我知道 unsigned int 不能保存负值。但下面的代码编译没有任何错误/警告。
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?
任何想法?
编辑
编译器:VC ++编译器
Compiler : VC++ compiler
strong>解决方案
Solution
需要使用警告级别4。
推荐答案
Microsoft Visual C ++:
Microsoft Visual C++:
警告C4245:'initializing':
从'int'
int',已签名/未签名的不匹配
warning C4245: 'initializing' : conversion from 'int' to 'unsigned int', signed/unsigned mismatch
在警告级别4上。
提供警告:
的负值
-0x00000000a'至
unsigned int'
warning: converting of negative value
-0x00000000a' to
unsigned int'
没有任何-W指令。
您必须使用:
gcc main.c -Wconversion
gcc main.c -Wconversion
p>
Which will give the warning:
警告:负整数隐式转换为无符号类型
warning: negative integer implicitly converted to unsigned type
请注意,-Wall不会启用此警告。
Note that -Wall will not enable this warning.
也许你只需要将警告级别提高。
Maybe you just need to turn your warning levels up.
这篇关于为什么编译器在带符号值分配给无符号整数时不会产生错误? - C ++的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!