I have been programming in c from quite some time. But never worked with programs where integer wrap around happens. I know that if integer is allocated 4 bytes then the range of integer becomes -2,147,483,648 to 2,147,483,647. And if we exceed the limit it just wraps around.
I was working with the following program to find out how wrap around happens.
#include <stdio.h>
int main() {
int n = 4, s = 2;
for (int i = 0; i < n; ++i)
{
for (int j = 0; j < n; ++j)
{
for (int k = 0; k < n; ++k)
{
s = 2 * s + 1;
}
}
}
printf("%d\n", s);
return 0;
}
I was using gdb to find out the values taken by the variable s. I found that when we are executing the innermost loop for 30th time the value of s becomes negative i.e -1073741825. Then for next iteration it becomes 2147483647 and for the 32nd iteration it becomes -1.
Then it remains as -1 forever. My doubt is why wrap around didn't happen after the value becomes -1. I know that the value of s in binary will be all 1's or FFFFFFFF in hex. And it wont change forever (internally it is updating but we can only see the last 32 bits so it's -1). But does the wrap around doesn't comes into picture this time? Is it compiler dependent? Or does gcc allow wrap around only once? Any kind of help would be appreciated. Thanks