Ndm Bcc
Ndm Bcc

Reputation: 9

Addition of two chars, example char a = 'A' and b = 'B'

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?

Upvotes: 0

Views: 151

Answers (3)

Karrer
Karrer

Reputation: 54

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.

Upvotes: 1

3Dave
3Dave

Reputation: 29051

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

Upvotes: 1

insaneThOughTS
insaneThOughTS

Reputation: 1

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.

Upvotes: 0

Related Questions