Help with if-else in C Program [duplicate]
Possible Duplicate:
What’s the “condition” in C interview question?
void main()
{
if(CONDITION)
printf("Hello ");
else
printf("World");
}
Replace CONDITION with such a condition that both the printf statements get executed. You can't have a loop or other things in main() I found this code online,i am trying to think the logic behind it but i cant. Please help me out Thanks
if(fork() == 0)
...
While I really like the idea behind the answer of rubber boots
I think there might be a more trivial answer. The description explicitly states that you may not have code inside main() but what about having a extra line outside?
#define else
void main()
{
if(1)
printf("Hello ");
else
printf("World");
}
Update Here is an alternative that was suggested byZan Lynx
in the comments. It only adds code between the parentheses around CONDITION:
void main()
{
if(1
#define else
)
printf("Hello ");
else
printf("World");
}
This is a bit like cheating but...
void main()
{
if (printf("Hello ") == 0)
printf("Hello ");
else
printf("World");
}
CONDITION = printf("Hello") == 0;
Here's another approach. It's not as good as fork
in that it tends to work only half the time (hence not completely solving the problem), but it is better in that the message never gets reversed.
#include <stdio.h>
int main() {
if ( ftell( stdout ) % 2 || ( printf( " " ), main() ) )
printf( "Hello " );
else
printf( "World\n" );
}
It first queries stdout
to see how much has been printed and whether the number of characters is odd. If so, it then prints a single character to reverse the parity and recurses. The recursive call sees an even number of characters and prints "hello" and returns 0. The 0 sends the top call into the else, printing "world."
The number of characters in the terminal must be odd for it to work.
Not exactly what you asked, but the following would at least print the same result as if when both printf were executed:
if(printf("Hello ") & 0)
printf("Hello ");
else
printf("World");
Leaping straight off the cliff pointed out by Potatoswatter, I offer the following:
#include <stdio.h>
#include <errno.h>
int main()
{
if ((errno == 42) || (errno=42, main()))
printf("hello, ");
else
printf("world.");
return 0;
}
C:\...>gcc -Wall q3472196.c C:\...>a hello, world. C:\...>
I did have to declare main and give it a return value to shut up a couple of warnings. There might even be something suitably evil defined in stdio.h itself so the we don't have to declare errno
.
#include <stdio.h>
main()
{
if (printf("Hello "),0)
printf("Hello ");
else
printf("World");
return 0;
}
精彩评论