[英]unsigned integer overflow error in gcc(TDM-GCC)?
#include <iostream>
#include <climits>
#include <cinttypes>
using namespace std;
int main()
{
uint16_t i = 0;
cout << USHRT_MAX << '\n' << i - 1 << '\n';
return 0;
}
Output 输出量
65535
-1
I expected two equal outputs, but it wasn't. 我期望两个相等的输出,但事实并非如此。 Isn't this a non-standard-compliant behaviour?
这不是不符合标准的行为吗?
*System: Windows7 *系统:Windows7
*Compile Option: g++ -o $(FileNameNoExt) $(FileName) -std=c++11 -Wall -Wextra *编译选项:g ++ -o $(FileNameNoExt)$(FileName)-std = c ++ 11 -Wall -Wextra
When C++ sees the expression 当C ++看到表达式时
i - 1
it automatically promotes i
and 1 to int
types, so the result of the expression is an int
, hence the output of -1. 它会自动将
i
和1提升为int
类型,因此表达式的结果为int
,因此输出为-1。
To fix this, either cast the overall result of the expression back to uint16_t
, or do something like 要解决此问题,请将表达式的整体结果转换回
uint16_t
,或执行类似的操作
i--;
to modify i
in-place, then print i
. 修改
i
,然后打印i
。
Hope this helps! 希望这可以帮助!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.