Monday, December 22, 2008

Tricky If Statement

Question:

Carefully go through the below snippet. I want the below program to print "Hello World".
Sit back, think for a while and try to find out what that "X" can be replaced with to get the desired output.

if (X)
{
printf ("Hello");
}
else
{
printf("World");

Solution:

Awesome, if you have found the answer already. If not, here is the answer for you...

!printf("Hello")

So the snippet should have been:

if (!printf("Hello")) // Hello is printed by this statement
{
printf ("Hello"); //This statement never gets executed
}
else
{
printf("World"); //World is printed by this statement


Explanation:

Before I start with the explanation, I would like to question you, "what does printf() return?" The clue lies in there! :)

Upon a successful return, the printf() function returns the number of characters printed (not including the trailing '\0' used to end output to strings). If the output was truncated due to this limit then the return value is the number of characters (not including the trailing '\0') which would have been written to the final string if enough space had been available. Thus, a return value of size or more means that the output was truncated. If an output error is encountered, a negative value is returned.

Thus, if(!printf("Hello")) does two things -
  1. Prints Hello
  2. Returns a non-zero value.

Notice the ! mark in-front of the printf() within the if condition. This makes the if condition fail and hence the else part gets executed which prints world resulting in the desired output:

Hello World

Variations:

With the explnation provided above, think what would the below line print out?

printf("%d",(printf("Hello")));

yeah, you got it right! The output will be:

Hello5

NOTE: 5 is the number of characters printed out by the "%d" of the outtermost printf() function. i.e., the total number of characters (in the string "hello") is printed out.

Let's try one more now...

Find the output -

int i=448; printf("%d\n",printf("%d",printf("%d",i)));

The output is -

44831

How??


The innermost printf("%d", i) prints 448 which is nothing but the value of variable i.
Hence the statement printf("%d",printf("%d",i)) will result in 4483 (here 3 is total number of characters/numbers the innermost printf printed out which is nothing but 448). The total number of characters/numbers the recent printf out printed out is 1 (remember?? the recent printf printed out 3, i.e., a single digit number). Hence the outtermost printf prints out 1. This results in the final result 44831.

Simple, yet interesting, Isn't it? :)

0 comments: