[英]Char addition does not have expected result in C
Can someone explain me how is this at the end有人可以解释一下最后这是怎么回事
a=?,b=?,c=-124
and not并不是
a=?,b=?,c=132
This is code:这是代码:
#include <stdio.h>
int main() {
char a = 'D', b='C', c='A';
a = c + 'D';
b = a + b + 'A';
c = b - a;
a = a - b + 'C';
b = b - 68;
printf("a=%c,b=%c,c=%d", a, b, c);
}
It appears on your system that char
is signed.您的系统上显示
char
已签名。 With ASCII, 'D'
, 'C'
and 'A'
are the same as the integers 68
, 67
, and 65
respectively.对于 ASCII,
'D'
、 'C'
和'A'
分别与整数68
、 67
和65
相同。
Add 68
to 65
and you get 133
.将
68
与65
,得到133
。 The binary representation of 133
is 10000101
. 133
的二进制表示是10000101
。 Notice that the most significant bit is 1
.请注意,最高有效位是
1
。 As you're using signed chars, twos complement comes into play, and the result is actually -123
.当您使用带符号的字符时,二进制补码开始发挥作用,结果实际上是
-123
。
Remember that a signed char
can hold values ranging from -128
to 127
, rather than 0
to 255
.请记住,有符号
char
可以保存范围从-128
到127
的值,而不是0
到255
。
Your C implementation has a signed eight-bit char
, likely uses ASCII, and, when converting an out-of-range value to a signed integer type, wraps modulo 2 w , where w is the width of (number of bits in) the type.您的 C 实现有一个带符号的八位
char
,可能使用 ASCII,并且在将超出范围的值转换为带符号的 integer 类型时,包装模 2 w ,其中w是宽度(位数)类型。 These are all implementation-defined;这些都是实现定义的; they may differ in other C implementations, with certain constraints.
它们在其他 C 实现中可能有所不同,但有一定的限制。
char a = 'D', b='C', c='A';
initializes a
to 68, b
to 67, and c
to 65.将
a
初始化为 68,将b
初始化为 67,并将c
为 65。
a = c + 'D';
assigns 65 + 68 = 133 to a
.将 65 + 68 = 133 分配给
a
。 Since 133 does not fit in char
, it wraps to 133 − 256 = −123.由于 133 不适合
char
,因此它会换行为 133 − 256 = −123。
b = a + b + 'A';
assigns −123 + 67 + 65 = 9 to b
.将 −123 + 67 + 65 = 9 分配给
b
。
c = b - a;
assigns 9 − −123 = 132 to c
.将 9 - -123 = 132 分配给
c
。 This wraps to 132 − 256 = −124.这将返回到 132 - 256 = -124。
a = a - b + 'C';
assigns −123 − 9 + 67 = −65 to a
.将 −123 − 9 + 67 = −65 分配给
a
。
b = b - 68;
assigns 9 − 68 = −59 to b
.将 9 − 68 = −59 分配给
b
。
printf("a=%c,b=%c,c=%d", a, b, c);
prints a=?,b=?,c=-124
because a
and b
are codes for abnormal characters and the value of c
is −124.打印
a=?,b=?,c=-124
因为a
和b
是异常字符的代码,并且c
的值为 -124。
It would seem your compiler treats char
as signed char
, so:您的编译器似乎将
char
视为signed char
,因此:
a = 'D', b='C', c='A'
a = c + 'D'
= 'A' + 'D'
= 65 + 68
= 133
a = c + 'D'
= 'A' + 'D'
= 65 + 68
= 133
but since a
is a signed char
, it becomes -123
(133-256)但由于
a
是有signed char
,它变成-123
(133-256)
b = a + b + 'A'
= -123 + 'C' + 'A'
= -123 + 67 + 65
= 9
b = a + b + 'A'
= -123 + 'C' + 'A'
= -123 + 67 + 65
= 9
c = b - a
= 9 - -123
= 9 + 123
= 132
c = b - a
= 9 - -123
= 9 + 123
= 132
a = a - b + 'C'
= -123 - 9 + 66
= -66
a = a - b + 'C'
= -123 - 9 + 66
= -66
b = b - 68
= 9 - 68
= `-59`` b = b - 68
= 9 - 68
= `-59`
So at the end, a = -66
, b = -59
, and c = 132
所以最后,
a = -66
, b = -59
和c = 132
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.