tags:

views:

2264

answers:

27

What is the answer to this C question:

What's the "condition" so that the following code snippet prints both HelloWorld !

if  "condition"
    printf ("Hello");
else
    printf("World");
+1  A: 

The if statement executes one or the other of the controlled statements (both printf in your example). No matter what you use for condition, that snippet will either print "Hello", or "World", but never both.

Edit: Okay, so it's a trick question and you can put whatever you like in the condition (including a call to an entire other function that does anything you want). But that's hardly interesting. I can't believe I got downmodded for giving a correct answer.

Greg Hewgill
I can't believe it either, whoever did it in my view was petty/lame. So here is some rep back :) There shouldn't be negative penalties for not being "clever" enough to see the solution and posting what you genuinely thought was correct.
freespace
+4  A: 
if ( printf("Hello")==0)

see [http://www.coders2020.com/what-does-printf-return]

(matt corrected my =, thanks, C is far away)

scoob
A: 
if(printf("Hello") == 1)
    printf("Hello")
else
    printf("World")
Jake Pearson
+33  A: 
if ( printf("Hello") == 0 )
    printf ("Hello");
else
    printf ("World");

:-)

Matt Dillard
Never thought of it.
fastcodejava
+1  A: 
if  (true) printf ("Hello"); if (false)
    printf ("Hello");
else
    printf("World");
travis
+11  A: 
"condition" === (printf("Hello"), 0)

Really lame:

int main() {
    if  (printf("Hello"), 0)
        printf ("Hello");
    else
        printf("World");
}

I prefer the use of the comma operator because you don't have to look up the return value of printf in order to know what the conditional does. This increases readability and maintainability. :-)

Frank Krueger
+1  A: 

This could work:

if (printf("Hello") - strlen("Hello"))
    printf("Hello")
else
    printf("World")

This snippet emphasizes the return value of printf: The number of characters printed.

Daren Thomas
A: 
if (printf("Hello") < 1)
    printf("Hello");
else
    printf("World");
Bill Ayakatubby
+4  A: 
#define CONDITION (0) if (0) {} else

or some such.

If you see such a question on an interview, run away as fast as you can! The team that asks such questions is bound to be unhealthy.

Edit - I forgot to clarify - this relies on "else" being matched with closest open "if", and on the fact that it's written as "if CONDITION" rather than if (CONDITION) - parenthesis would make the puzzle unsolvable.

Arkadiy
A: 

Greg wrote:

No matter what you use for condition, that snippet will either print "Hello", or "World", but never both.

Well, this isn't true, but why you would want it to print both, I can't find a use case for. It's defeating the point of having an if statement. The likely "real" solution is to not use an if at all. Silly interview questions... :)

infralite
A: 

Very interesting guys, thanks for the answers. I never would have thought about putting the print statement inside the if condition.

Here's the Java equivalent:

 if ( System.out.printf("Hello").equals("") )
  System.out.printf("Hello");
 else
  System.out.printf("World");
redspike
+2  A: 

Without knowing the return value of printf off the top of your head:

if (printf("Hello") && 0)
    printf("Hello");
else
    printf("World");
+8  A: 

If it is on Unix:

if  (fork())
    printf ("Hello");
else
    printf("World");

Ofcoures that doesn't guarantee the order 0f the prints

GowriKumar
+1  A: 

Solution 1:

int main(int argc, char* argv[])
{   
    if( argc == 2 || main( 2, NULL ) )
    {
     printf("Hello "); 
    }
    else
    {
     printf("World\n");
    }
    return 0;
}

Solution 2 (Only for Unix and Linux):

int main(int argc, char* argv[])
{   
    if( !fork() )
    {
     printf("Hello "); 
    }
    else
    {
     printf("World\n");
    }
    return 0;
}
A: 

No love for exit?

if(printf("HelloWorld"), exit(0), "ByeBye") 
    printf ("Hello");
else
    printf ("World");
Johannes Schaub - litb
A: 

Dont use an if else block then.

EDIT to Comment.

It might then mean that the code be in both blocks, or before/after the block if it is required to run in both cases.

astander
what should be code in 'if' condition if we want to execute code in both the blocks??
+2  A: 

So... you want to execute the code inside the if block... and the code inside of the else block... of the same if/else statement? Then... you should get rid of the else and stick taht code in the if.

if something
  do_this
  do_that
end

The else statement is designed to execute only if the if statement is not executed and vice-versa, that is the whole point. This is an odd question...

Ed Swangren
+1  A: 

Just put the code before or after the if..else block.

Alternatively, if you have an "if, else if, else" block where you want to execute code in some (but not all) branches, just put it in a separate function and call that function within each block.

Michael Stum
+1  A: 

Comment the "else" ;)

if(foo)
{
    bar();
}
//else
{
    baz();
}
Tordek
Great answer! Good use of comment.
fastcodejava
+10  A: 

Buckle your seatbelts:

#include <stdio.h>
#include <setjmp.h>

int main()
{
    jmp_buf env;

    if (!setjmp(env))
    {
        printf("if executed\n");
        longjmp(env, 1);
    }
    else
    {
        printf("else executed\n");
    }

    return 0;
}

Prints:

if executed
else executed

Is this what you mean? I doubt it, but at least it's possible. Using fork you can do it also, but the branches will run in different processes.

Eli Bendersky
Beware: you cannot portably assign the return value from the setjmp() macro.
Jonathan Leffler
@jonathan - you're right, fixed the code. However, I wonder whether there's any compiler these days that doesn't handle it correctly. Many C "exception" frameworks based on setjmp use its return value saved to a flag
Eli Bendersky
In practice, it probably works; I certainly don't know of a platform where it doesn't work - but I've not investigated either, because debugging the failure would be painful (at best). Assigning the return value of `setjmp()` is undefined behaviour; anything could happen (including 'it works as expected or desired').
Jonathan Leffler
+1 for absolute filthiness.
Stephen Canon
+4  A: 

This sounds to me like some interview puzzle as there is no point in doing that in a production code.
I hope this is close to what you want.


#include <stdio.h>

int main()
{
 static int i = 0 ;
 if( i++==0 ? main(): 1)
  printf("Hello,");
 else
  printf("World\n");

 return 0 ;
}

prints Hello, World

Neeraj
Thanks for answer Neeraj!
A: 

use a goto, one of the single most underused keywords of our day

Dasuraga
And quite possibly one of the most dangerous, as Dijkstra and others have mentioned.
Matthew
goto isn't nearly as dangerous as the array dereference operator.
Steve Jessop
+3  A: 

The basic answer is that in the ordinary course of events you neither want to execute both the statements in the 'if' block and the 'else' block in a single pass through the code (why bother with the condition if you do) nor can you execute both sets of statements without jumping through grotesque hoops.

Some grotesque hoops - evil code!

    if (condition == true)
    {
         ...stuff...
         goto Else;
    }
    else
    {
Else:
        ...more stuff...
    }

Of course, it is a plain abuse of (any) language because it is equivalent to:

    if (condition == true)
    {
         ...stuff...
    }
    ...more stuff...

However, it might achieve what the question is asking. If you have to execute both blocks whether the condition is true or false, then things get a bit trickier.

    done_then = false;
    if (condition == true)
    {
Then:
         ...stuff...
         done_then = true;
         goto Else;
    }
    else
    {
Else:
        ...more stuff...
        if (!done_then) goto Then;
    }
Jonathan Leffler
+1 Haha, just wanted to post that too.
Johannes Schaub - litb
An 'even more evil' version of the code reverses the labels (so the 'then' clause has a label 'Else' and vice versa). And maybe the 'ultimate' in evil-ness insists that the code blocks are executed in the same order regardless of the result of the condition (which can be done, of course). But the requirements are then getting so far-fetched as to be ridiculous - if they weren't already!
Jonathan Leffler
+2  A: 
int main()
{
    runIfElse(true);
    runIfElse(false);

    return 0;
}

void runIfElse(bool p)
{
    if(p)
    {
     // do if
    }
    else
    {
     // do else
    }
}
Dustin E
It isn't clear what the question means by 'run', is it? +1 for distorting the question a different way.
Jonathan Leffler
A: 

Cheeting with an empty else statement:

if (condition)
    // do if stuff
else;
    // do else stuff

If you don't like the fact that else; is actually an empty else statement try this:

for (int ii=0; ii<2; ii++)
{
    if (condition && !ii)
        // do if stuff
    else
    {
        // do else stuff
        break;
    }
}
lpz
+1  A: 

Why use if-else in this case?

fastcodejava