I have a piece of code from a job that I'm not sure about. I feel confident that I know the answer, but I just want to double check with the community that there I forgot something. The name is basically safe coding, and the question is only to explain the results.
int main() {
unsigned int i = 1;
unsigned int c = 1;
while (i > 0) {
i = i*2;
c++;
}
printf("%d\n", c);
return 0;
}
My reasoning is this:
At first glance, you can imagine that the code will work forever, given that it is initialized with a positive value and is constantly growing. This, of course, is wrong, because in the end the value will be so great that it will lead to overflow of integers. This, in turn, is also not entirely true, because ultimately it will cause the variable "i" to sign, making the last bit equal to 1 and, therefore, be considered a negative number, so the loop ends. Thus, it does not write to unallocated memory and, therefore, causes an integer overflow, but rather violates the data type and, therefore, leads to the end of the cycle.
I am sure this is the reason, but I just want to double check. Any opinions?