Given this simple code snippet:
#include <stdio.h>
#include <stdint.h>
int main() {
int8_t a = -1;
printf("Dec: %d, Hex: %hhx\n", a, a);
int8_t b = a + 1;
printf("Dec: %d, Hex: %hhx\n", b, b);
return 0;
}
The result is:
Dec: -1, Hex: ff
Dec: 0, Hex: 0
which makes sense and it looks my system is using two's complement to implement negative integers.
But a is an 8-bit signed integer. When adding 1 to 0xff, it should result in an integer overflow. And according to this question, signed integer overflow is not a defined behavior.
Thus, how does addition work for an 8-bit negative integer such that it avoids undefined behavior?
Does it have something to do with integer promotion? If so, how does it work at a low level?
Update: I appreciate all answers. After reading all the answers, I am still confused about promotion and wraparound. E.g., when an signed integer with the biggest data type is used, does it still do promotion and wraparound? Given this code:
int main() {
intmax_t a = -1;
printf("Dec: %ld, Hex: %lx\n", a, a);
intmax_t b = a + 1;
printf("Dec: %ld, Hex: %lx\n", b, b);
return 0;
}
The result is:
Dec: -1, Hex: ffffffffffffffff
Dec: 0, Hex: 0
The result is still correct and I would like to know why since there is no more promotion can be done here, right?
Also, I am especially confused about the statement of "0xff + 1" versus "-1 + 1" such as:
You're not actually adding 1 to 0xff. You're adding 1 to -1. It's just that -1 is represented as 0xff in a
int8_t.
I am sorry, but in the computer, as far as I know, there is no idea of "-1". It's using binary representation of "-1" to do all kinds of addition, right? So, my question is that when binary representation is used to conduct addition 0xffffffffffffffff + 1, why doesn't it overflow. What's happening under the hood?
Unsigned integers do not overflow only wrap around. When you analyze how two's complement numbers work under the hood - you analyze unsigned integers.
Signed integers overflow (or underflow) occurs when it gets a value larger than the maximum or minimum signed value which can be stored in that integer.
For
int8_tthose values are-128&127. So when you want to add or subtract1only-128 - 1or127 + 1will result in overflow.-1 + 1does not.How does it work under the hood?
-1 in two's complement (8 bits):
First, represent
1in binary, then invert the bits and add one to find -1.So,
-1is represented as11111111in two's complement.+1in binary (8 bits):00000001