arith-overflow
#include <stdio.h> | |
int main() { | |
// Given an unsigned char, if we add 1 to the max value an unsigned char can have, | |
// we strangely get the correct value, which should have overflown the char... | |
unsigned char a = 255; | |
printf("%lu + 1 == %d \n", a, a + 1); | |
// Output: 255 + 1 == 256 | |
// When we take this value and assign it to an unsigned char, and look at the | |
// value again we get ... | |
unsigned char b = a + 1; | |
printf("%lu + 1 == %d \n", a, b); | |
// Output: 255 + 1 == 0 | |
// This is because in C all arithmetic UP CASTS if there is an overflow! | |
// Looking at the type of the result of a + 1 | |
printf("sizeof a == %d; sizeof a+1 == %d\n", sizeof(a), sizeof(a+1)); | |
// Output: sizeof a == 1; sizeof a+1 == 4 | |
// As you can see the sizeof a is 1 byte, and the sizeof a+1 is 4 bytes | |
// | |
unsigned char i = 0; | |
unsigned char j = 255; | |
printf(" 0 - 255 == %d\n", i - j); | |
// Output: 0 - 255 == -255 | |
printf(" 0 - 255 == %d\n", (unsigned char)(i - j)); | |
// Output: 0 - 255 == 1 | |
// You can see that this can get confusing if you do not explicitly cast arithmetic | |
printf("-128/-1 == %d\n", (signed char)(-128/-1)); | |
// Output: -128/-1 == -128 | |
// WAT? :) | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment