a+b的值和char类型

Value of a+b and char type

我正在使用 C++ 工作,我不得不(作为练习)在纸上写下 2 个答案。 第一个问题:如果我们有如下变量的声明和初始化:

unsigned char x=250, z=x+7, a='8';

表达式的值是多少?

z|(a-'0') // (here | is bitwise disjunction)

我们有unsigned char,所以数字z=x+7减少了mod256,因此,将数字写成二进制后,答案是9。


下一题:a和b是int变量,a=1b=32767.

int的取值范围是[-32768, 32767]。我们这里没有无符号类型。我的问题是:a+b 的值是多少?如果某个变量的值大于该数据类型的范围,这如何处理有符号数据类型?

C++中没有operator+(unsigned char, unsigned char),它先将这些unsigned char参数提升为int,然后才做加法,所以表达式的类型是int.

然后 int 的值太大而不适合 unsigned char 被转换为 unsigned char

标准说:

A prvalue of an integer type can be converted to a prvalue of another integer type. A prvalue of an unscoped enumeration type can be converted to a prvalue of an integer type. If the destination type is unsigned, the resulting value is the least unsigned integer congruent to the source integer (modulo 2**n where n is the number of bits used to represent the unsigned type). [ Note: In a two’s complement representation, this conversion is conceptual and there is no change in the bit pattern (if there is no truncation). — end note ]

The next question: a and b are int variables, a=1 and b=32767.

[...]My question is: what is the value of a+b?

undefined behavior。我们不能告诉你它会是什么。我们可以做出合理的猜测,但就 C++ 而言,有符号整数溢出是未定义的行为。

第二题,答案未定

你可以这样自己验证:

#include <iostream>

using namespace std;

int main()
{
    int a = 1;
    int b = 32767;
    int c = a+b;
    cout << c << endl;
}

结果将取决于您的机器。