problems adding 2 characters together in c

2019-09-02 19:54发布

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?

1条回答
▲ chillily
2楼-- · 2019-09-02 20:53

Probably because your chars 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;
查看更多
登录 后发表回答