我的代码中有以下行
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;
谢谢
由于它是一个编译器错误,这个答案是特定于 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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!