Update: This post was originally shared on this blog
Let me share a very interesting C programming puzzle that I learnt from one of my friends.
Consider the following code-snippet written in the C programming language.
int i; for (i = 0; i < 6; i--) printf(".");
This code invokes undefined behaviour. The value in variable
idecrements to INT_MIN after |INT_MIN| + 1 iterations. In the next iteration, there is a negative overflow which is undefined for signed integers in C. On many implementations though, INT_MIN − 1 would result in INT_MAX which is not less than 6 and thus the loop would terminate. With such implementations, this code would print |INT_MIN| + 1 dots. With 32-bit integers, that would be 2147483649 dots. However, it could also be optimized into an endless loop by the compiler if it wants to exploit the fact that a negative overflow for signed integers is undefined. gcc in fact does optimize that to an endless loop if you compile it with the
Now, here is the puzzle.
An obvious solution is:
int i; for (i = 0; i < 6; i++) printf(".");