Why compiler is not giving error when signed value is assigned to unsigned integer? - C++(为什么将有符号值分配给无符号整数时编译器不会出错?- 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' tounsigned 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++的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:为什么将有符号值分配给无符号整数时编译器不会出错?- C++
基础教程推荐
- 随机插入/删除的综合向量与链表基准 2022-01-01
- 与 CAS 的原子交换(使用 gcc 同步内置函数) 2022-01-01
- 为什么我们不能使用“虚拟继承"?在 COM 中? 2022-01-01
- 如何在 C++ 中正确使用命名空间? 2022-01-01
- 如何部分禁用 cmake C/C++ 自定义编译器检查 2021-01-01
- 如何更改 SysDateTimePick32 或 CDateTimeCtrl 的背景颜色? 2022-01-01
- C++:获取传递给函数的多维数组的行大小 2021-01-01
- c++ STL设置差异 2022-01-01
- 将不可复制的闭包对象传递给 std::function 参数 2021-01-01
- 提升 ASIO 流缓冲 2021-01-01
