Visual Studio 在MSVC中减去无符号整数时顺序重要吗?[重复]

rekjcdws  于 7个月前  发布在  其他
关注(0)|答案(1)|浏览(63)

此问题在此处已有答案

warning C4146 minus operator on unsigned type(1个答案)
How can I fix error code C4146 "unary minus operator applied to unsigned type.result still unsigned"?(2个答案)
error C4146: unary minus operator applied to unsigned type, result still unsigned(5个答案)
28天前关闭。
当使用无符号整数(size_t)时,MSVC会抱怨如下:
(It看起来像gcc和clang编译这些。)

size_t a = 1, b = 2;    
-a;   // C4146: unary minus operator applied to unsigned type, result still unsigned.
-a+b; // Also the same error as above.
b-a;  // Compiles well.

字符串
-a-a+b的错误消息是可以理解的,因为size_t是无符号类型。
b-a是如何编译的?
这是一个正确的方法来减去两个无符号类型的整数?

sgtfey8w

sgtfey8w1#

问题的关键在于,在C++中,有 * 两种不同的减运算符--一元和二元。* 所以,与数学不同,b-a不等同于b + (-a),正如@molbdnilo评论的那样。看起来gcc和clang编译了问题中的代码。
我只是简单地想做数学,这是一个很大的错误。谢谢所有的评论。

编辑:正如@PeteBecker评论的那样,问题中的代码都是有效的,但错误与编译器设置有关。

我在Visual Studio中发现了一些与“将警告视为错误”相关的设置。在项目属性设置页面中:
1)C/C++ -> General ->“Treat warnings as errors”:是(/WX)或否(/WX-
  C/C++ ->常规->“SDL检查”:是(/sdl)或否(/sdl-
  C/C++ ->高级->“将特定警告视为错误”
在我的例子中,1)是“No”,3)是空的,但2)是“Yes”,这就是错误的原因。/sdl(启用其他安全检查)编译器选项将警告提升到错误。有关详细信息,请参阅MSDN "Compiler warning (level 2) C4146"

相关问题