Visual Studio 2015-编译器警告(等级2)C4146 [英] Visual Studio 2015 - Compiler Warning (level 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编译器看到此问题吗?
- 如何定义数据类型?
- 如何检查范围?
- 为什么似乎忽略了已签名"分配?
- Has anyone seen this issue with Visual Studio 2015 compiler?
- How is it defining the data types?
- How is the range checked?
- Why does it seem to ignore the "signed" assignment?
谢谢
推荐答案
由于它是编译器错误,因此此答案特定于 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的类型 整数,但无符号整数.
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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!