DocMogrog DocMogrog - 2 months ago 10
C Question

Sum of two characters

First of all, this is the small program that I've made:

#include <stdio.h>
int main(void) {
char z = '"' + '!';
printf("%c\n", z);
return 0;
}


The console give me 'C'. So I think this is normal. I've read that when we compute characters they are turning into decimal value.

ASCII ----> decimal
'"' ----> 34
'!"----> 33

34 + 33 = 67
C-----> 67


Everything seems ok.

But, when I try to do : 'a' + 'b', it gives me '\303'. Why?

a ---> 97
b ---> 98

97 + 98 = 195.


195 is outside of the ASCII table, so I was expecting to have a error message.

Thank you in advance for your help, and thanks to be comprehensive about my broken English!

Answer

Sadly, it won't give an error message. As is common with C, instead of errors it has "undefined behavior", which makes debugging a lot of problems difficult, because it is syntactically valid but technically wrong. This is a lot of the reason why exceptions were added in C++, but this is getting off topic.

As mentioned in comments, 'a' + 'b' is in fact 195, which in octal is 303. Reinterpreting the unsigned 195 to a signed value is -61 (see below for more on this). In both cases, they are outside of the printable range for ascii characters. On my console it prints a � but this is non-standard, different consoles will print different things there.

The fix is to make sure you are passing meaningful data to printf before calling it, and no expecting printf to do the work of detecting it.

Side note: you should turn on all warnings with your compiler, they often catch many of these problems.

Side note 2: if 'a' + 'b' yielded a signed char, then it would be -61, but it in fact is a 32 bit int. You can check this with sizeof('a' + 'b') returning 4. So the number being printed is 195, which still doesn't map to a valid character in the ASCII table.