Home > Software design >  Addition of two chars, example char a = 'A' and b = 'B'
Addition of two chars, example char a = 'A' and b = 'B'

Time:11-29

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?

CodePudding user response:

char is a signed type, so it can only represent values from -127 to 127.

Adding 'a' to 'b' is the same as adding their ASCII values (97 and 98 respectively), for a result of 195. The first bit is the sign bit, so you get -61.

Using unsigned char gives the result that you expect.

#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

CodePudding user response:

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.

  • Related