Monday, November 28, 2011

Loopy C puzzle


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 i decrements 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 -O3option.
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. 

Update: This post was originally shared on this blog


              Solutions are here