I just came across an interesting case but I can't find any information about it and I was wondering if anyone here might know the answer.
So I have the macro INT_MAX which is the largest possible number an int can store on my operating system.
the following if statement has some weird behavior:
#include <stdio.h>
#include <limits.h>
int main(int argc, const char* argv[]) {
int maxValue = INT_MAX;
printf("INT_MAX: %d\n", maxValue);
printf("INT_MAX + 1: %d\n", maxValue + 1);
if (INT_MAX < maxValue + 1) {
printf("no overflow\n");
} else {
printf("overflow\n");
}
return 0;
}
by running this program we get the value of INT_MAX and the overflow of INT_MAX followed by overflow.
if I switch INT_MAX with the variable maxValue the 'else' is executed instead and "no overflow" is printed. I assume this means that the if statement or < operator is checking if both the left and right values passed to it are the same and instead of doing the actual calculation it simply returns 1 as it sees that on the right hand side we're adding a positive value to the same variable.
So is this what is actually happening or is it something else entirely?
Thanks!
edit: INT_MAX not MAX_INT
Aucun commentaire:
Enregistrer un commentaire