Char addition does not have expected result in C

86 views Asked by At

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);
}
3

There are 3 answers

0
Eric Postpischil On BEST ANSWER

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 2w, where w is the width of (number of bits in) the type. These are all implementation-defined; they may differ in other C implementations, with certain constraints.

char a = 'D', b='C', c='A'; initializes a to 68, b to 67, and c to 65.

a = c + 'D'; assigns 65 + 68 = 133 to a. Since 133 does not fit in char, it wraps to 133 − 256 = −123.

b = a + b + 'A'; assigns −123 + 67 + 65 = 9 to b.

c = b - a; assigns 9 − −123 = 132 to c. This wraps to 132 − 256 = −124.

a = a - b + 'C'; assigns −123 − 9 + 67 = −65 to a.

b = b - 68; assigns 9 − 68 = −59 to 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.

0
Chris On

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.

0
SGeorgiades On

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