[英]Why is the code giving output of -61 when I do cout c but 195 when I cout a+b?
I wrote the following code, I do not understand why I get -61 when I cout<<int(c).我写了以下代码,我不明白为什么当我 cout<<int(c) 时我得到 -61。
int main() {
char a= 'a';
char b= 'b';
char c= a+b;
cout<<int(a)<<" ";
cout<<int(b)<<" ";
cout<<int(a+b)<<" ";
cout<<int(c)<<" ";
return 0;
char type may be signed or unsigned. char 类型可以是有符号或无符号的。 It is tuned by a compiler flag.
它由编译器标志调整。 Char type is signed by default in most compilers and consists of 8 bits, one bit is for sign and 7 bits are for a numeric values.
Char 类型在大多数编译器中默认是有符号的,由 8 位组成,1 位用于符号,7 位用于数值。 Thus the signed char represents numeric values from -128 up till 127. Such set of values is a ring.
因此,有符号字符表示从 -128 到 127 的数值。这样的一组值是一个环。 Further increasing of 127 returns to -128.
进一步增加 127 返回 -128。
As you see, 97 and 98 are ASCII codes of 'a' and 'b'.如您所见,97 和 98 是 'a' 和 'b' 的 ASCII 码。 Any types smaller than int are promoted to int before applying operators, thus a+b is int 195. If you assign 195 to a signed char, the signed value overflow happens, that is considered as the undefined behaviour, because signed values may be represented differently than above.
在应用运算符之前,任何小于 int 的类型都会被提升为 int,因此 a+b 是 int 195。如果将 195 分配给有符号字符,则会发生有符号值溢出,这被认为是未定义的行为,因为可以表示有符号值与上面不同。 In you case, 195 is over 127 on 68, since127+1 is -128, thus 127+68 127+1+67 is -128+67 is -61.
在您的情况下,195 在 68 上超过 127,因为 127+1 是 -128,因此 127+68 127+1+67 是 -128+67 是 -61。
C++ does not have operator+(char,char)<\/code> .
C++ 没有
operator+(char,char)<\/code> 。
Therefore when you add two
char<\/code> s the arguments are promoted to
int<\/code> s and result is
int<\/code> .
因此,当您添加两个
char<\/code>时,参数将提升为
int<\/code> ,结果为
int<\/code> 。
Further initializing a
char<\/code> c with
int<\/code> (value
195<\/code> ) that is outside of range of
char<\/code> of your compiler (seems to be
-128<\/code> ...
127<\/code> ) is implementation defined behavior by C++ standard.
使用超出编译器
char<\/code>范围(似乎是
-128<\/code> ...
127<\/code> )的
int<\/code> (值
195<\/code> )进一步初始化
char<\/code> c 是 C++ 标准的实现定义行为。
On your implementation the behavior looks common ... so effectively for values
x > 127<\/code> the result is
x - 256<\/code> .
在您的实现中,行为看起来很常见......对于值
x > 127<\/code>非常有效,结果是
x - 256<\/code> 。
The
195 - 256<\/code> is value
-61<\/code> .
195 - 256<\/code>是值
-61<\/code> 。
If you want 8 bit integer that can have
195<\/code> in range you should use
unsigned char<\/code> or
uint8_t<\/code> .
如果您想要
195<\/code>范围内的 8 位整数,您应该使用
unsigned char<\/code>或
uint8_t<\/code> 。
"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.