'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);
}
Solution 1:[1]
It appears on your system that char is signed. With ASCII, 'D', 'C' and 'A' are the same as the integers 68, 67, and 65 respectively.
Add 68 to 65 and you get 133. The binary representation of 133 is 10000101. Notice that the most significant bit is 1. As you're using signed chars, twos complement comes into play, and the result is actually -123.
Remember that a signed char can hold values ranging from -128 to 127, rather than 0 to 255.
Solution 2:[2]
It would seem your compiler treats char as signed char, so:
a = 'D', b='C', c='A'
a = c + 'D' = 'A' + 'D' = 65 + 68 = 133
but since a is a signed char, it becomes -123 (133-256)
b = a + b + 'A' = -123 + 'C' + 'A' = -123 + 67 + 65 = 9
c = b - a = 9 - -123 = 9 + 123 = 132
a = a - b + 'C' = -123 - 9 + 66 = -66
b = b - 68 = 9 - 68 = `-59``
So at the end, a = -66, b = -59, and c = 132
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Chris |
| Solution 2 |
