简体   繁体   English

gcc(TDM-GCC)中的无符号整数溢出错误?

[英]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! 希望这可以帮助!

i is promoted to an int before the evaluation of i - 1 , so the expression i - 1 is itself evaluated as a signed integer ( int ), try : i在评估i - 1 之前被提升为int,因此表达式i - 1本身被评估为有符号整数( int ),请尝试:

cout << USHRT_MAX << '\n' << (uint16_t)(i - 1) << '\n';

Live Demo 现场演示

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM