为什么将有符号值分配给无符号整数时编译器不会出错?- C++

我知道 unsigned int 不能保存负值.但以下代码编译时没有任何错误/警告.

unsigned int a = -10;

当我打印变量 a 时,打印出错误的值.如果无符号变量不能保存有符号值,为什么编译器允许它们编译而不给出任何错误/警告?

有什么想法吗?

编辑

编译器:VC++编译器

解决方案

需要使用警告级别 4.

解决方案

Microsoft Visual C++:

<块引用>

警告 C4245:正在初始化":从int"到unsigned"的转换int', 有符号/无符号不匹配

处于警告级别 4.

G++

给我警告:

<块引用>

警告:负值的转换-0x00000000a' 到 unsigned int'

没有任何 -W 指令.

海湾合作委员会

您必须使用:

<块引用>

gcc main.c -Wconversion

哪个会发出警告:

<块引用>

警告:负整数隐式转换为无符号类型

请注意 -Wall 不会启用此警告.


也许你只需要提高你的警告级别.

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.

解决方案

Microsoft Visual C++:

warning C4245: 'initializing' : conversion from 'int' to 'unsigned int', signed/unsigned mismatch

On warning level 4.

G++

Gives me the warning:

warning: converting of negative value -0x00000000a' to unsigned int'

Without any -W directives.

GCC

You must use:

gcc main.c -Wconversion

Which will give the warning:

warning: negative integer implicitly converted to unsigned type

Note that -Wall will not enable this warning.


Maybe you just need to turn your warning levels up.

相关文章