Let me share a very interesting C programming puzzle that I learnt from one of my colleagues.
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.
Add or modify exactly one operator in the following code such that it prints exactly 6 dots.
int i; for (i = 0; i < 6; i--) printf(".");
An obvious solution is:
int i; for (i = 0; i < 6; i++) printf(".");
There are at least 3 other solutions. I found one of them very interesting. I'll discuss the interesting solution tomorrow. Till then, feel free to try and post your solutions below as comments.
Update: The discussion on the solution is now available at: Solutions to 'Loopy C Puzzle'.