Would it be possible to print Hello
twice using single condition
?
if \"condition\"
printf (\"Hello\");
else
printf(\"World\");
This sounds to me like some interview puzzle. 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
"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. :-)
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");
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.
if (printf("Hello") < 1)
printf("Hello");
else
printf("World");
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... :)