Reputation: 334
I'm currently trying to add 2 characters in c i.e.
char a = 127;
char b = 127;
char c = a + b;
printf("%d\n", c);
which prints out 4294967278, I'm actually having problems anytime I add 2 numbers together where the resultant ASCII value would be greater than 127, what is happening here? aren't characters 8 bits or 256 possible numbers? so adding values that would be less than 256 should work no?
Upvotes: 0
Views: 138
Reputation: 20244
Probably because your char
s are signed
and can hold values from -128 to 127. By using
char c = a + b;
you have an overflow and overflow of signed char
results in Undefined Behavior. You can use an unsigned char
to get rid of the problem:
unsigned char c = a + b;
Upvotes: 2