为什么编译器在带符号值分配给无符号整数时不会产生错误? - C ++ [英] Why compiler is not giving error when signed value is assigned to unsigned integer? - C++

查看:324
本文介绍了为什么编译器在带符号值分配给无符号整数时不会产生错误? - C ++的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

  unsigned int a = -10; 

当我打印变量 时,如果无符号变量不能容纳带符号的值,为什么编译器允许他们编译而不给出任何错误/警告?



任何想法?



编辑



编译器:VC ++编译器



strong>解决方案



需要使用警告级别4。

解决方案

Microsoft Visual C ++:




警告C4245:'initializing':
从'int'
int',已签名/未签名的不匹配


在警告级别4上。


$ b b

G ++



提供警告:



-0x00000000a'到


$ h b $ b


gcc main.c -Wconversion


p>


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


请注意,-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.

这篇关于为什么编译器在带符号值分配给无符号整数时不会产生错误? - C ++的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆