Why does this program output a negative value?
#include <stdio.h>
int main() {
char a = 'a', b = 'b', c;
c = a + b;
printf("%d", c);
}
Shouldn't these values be converted into ASCII then added up?
On the most common platforms, char
is a signed type which can represent values from -127
to +128
. You appear to be using a platform on which char
has these properties.
Note that on some platforms, char
is unsigned, so that the range of representable values is 0
to 255
. However, you do not appear to be using such a platform.
Adding 'a'
to 'b'
is the same as adding their ASCII values ( 97
and 98
respectively), for a result of 195
. This result is not representable as a char
on your platform. In many implementations, the first bit is a sign bit, so you get -61
.
Using unsigned char
gives the result that you expect for printable 7-bit ASCII characters.
#include <stdio.h>
int main() {
char a = 'a', b = 'b';
unsigned char c;
c = a + b;
printf("%d\n",a);
printf("%d\n",b);
printf("%d\n", c);
}
Outputs:
97
98
195
a = 97
b = 98
a+b = 195
195 is out of the signed 8-bit range (-128... 127)
195 = 0b11000011
This equals -61 in signed 8-bit representation.
As explained by 3Dave char is a signed type and adding up two variables of such type can lead to overflow and it produces a negative result. Even if you use unsigned char
this sum can result in an overflow, but not with negative value.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.