ctwos-complementunsigned-char

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

  • 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.