Would it be possible to print Hello
twice using single condition
?
if \"condition\"
printf (\"Hello\");
else
printf(\"World\");
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;
}
}
No love for exit
?
if(printf("HelloWorld"), exit(0), "ByeBye")
printf ("Hello");
else
printf ("World");
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;
}
#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.
int main()
{
runIfElse(true);
runIfElse(false);
return 0;
}
void runIfElse(bool p)
{
if(p)
{
// do if
}
else
{
// do else
}
}
Comment the "else" ;)
if(foo)
{
bar();
}
//else
{
baz();
}