Visual Studio 2015 - Compiler Warning (level 2) C4146(Visual Studio 2015 - 编译器警告(级别 2)C4146)
问题描述
我的代码中有以下行
signed int test_case= -2147483648;
产生错误:
C4146 一元减运算符应用于无符号类型,结果仍然无符号
C4146 unary minus operator applied to unsigned type, result still unsigned
但这仍然是有符号整数类型的数据范围:
but this is still with the data range of teh signed integer type:
__int32 有符号、有符号 int、int –2,147,483,648 到 2,147,483,647
__int32 signed, signed int, int –2,147,483,648 to 2,147,483,647
奇怪的是将它分配为 signed long 给出了同样的错误,即
The strange things is assigning it as signed long gives this same error, i.e.
signed long test_case= -2147483648;
以下更改编译正常:
signed int test_case= -2147483647;
signed int test_case= 2147483649;
signed long test_case= -214748364800;
- 有人在 Visual Studio 2015 编译器中看到过这个问题吗?
- 它是如何定义数据类型的?
- 如何检查范围?
- 为什么它似乎忽略了已签名"分配?
谢谢
推荐答案
由于它是一个编译器错误,这个答案是特定于 MSVC 的,它是错误的 从 iso C++ 的角度来看.有关正确和标准的答案,请参阅@Bathsheba 的答案.(我鼓励 OP 接受正确答案,而不是为未来的读者接受此答案).
Since it is a compiler bug, this answer is specific to MSVC and it is wrong from iso C++ perspective. For the correct and standard answer please see @Bathsheba answer. (I encourage the OP to accept the correct answer instead of this answer for future readers).
来自 MSDN:
计算数字 2147483648.因为它大于最大整数值 2147483647,2147483648 的类型不是int,但无符号整数.
The number 2147483648 is evaluated. Because it is greater than the maximum integer value of 2147483647, the type of 2147483648 is not int, but unsigned int.
换句话说,编译器会将 -2147483648 处理为 -
和 2147483648
而不是 -2147483648
.所以 2147483648
部分被认为是 unsigned int
,因为它比 int
大.然后编译器应用导致此警告的 -
运算符.
In other words, the compiler will deal with -2147483648 as -
and 2147483648
not as -2147483648
. So the 2147483648
part is considered as unsigned int
since it is bigger than int
. and then the compiler applies the -
operator which is leading to this warning.
解决方案:
auto test_case= -2147483648ll;
这篇关于Visual Studio 2015 - 编译器警告(级别 2)C4146的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:Visual Studio 2015 - 编译器警告(级别 2)C4146
基础教程推荐
- 使用从字符串中提取的参数调用函数 2022-01-01
- 如何使图像调整大小以在 Qt 中缩放? 2021-01-01
- 为 C/C++ 中的项目的 makefile 生成依赖项 2022-01-01
- Windows Media Foundation 录制音频 2021-01-01
- 如何在不破坏 vtbl 的情况下做相当于 memset(this, ...) 的操作? 2022-01-01
- 管理共享内存应该分配多少内存?(助推) 2022-12-07
- 从 std::cin 读取密码 2021-01-01
- 在 C++ 中循环遍历所有 Lua 全局变量 2021-01-01
- 如何“在 Finder 中显示"或“在资源管理器中显 2021-01-01
- 为什么语句不能出现在命名空间范围内? 2021-01-01