Help with if-else in C program

Possible duplicate:
What is the “condition” in the interview question C?

void main() { if(CONDITION) printf("Hello "); else printf("World"); } 

Replace CONDITION with the condition that both printf statements are executed. You cannot have a loop or other things basically () I found this code on the Internet, I'm trying to think about logic, but I can't. Please help me thanks

+4
source share
8 answers

This is a bit of a hoax, but ...

 void main() { if (printf("Hello ") == 0) printf("Hello "); else printf("World"); } 
+3
source
  if(fork() == 0) ... 
+35
source

While I really like the rubber boots answer idea, I think there may be a more trivial answer. The description clearly states that you may not have code inside main (), but what about the external line?

 #define else void main() { if(1) printf("Hello "); else printf("World"); } 

Refresh . Here is an alternative suggested by Zan Lynx in the comments. It only adds code between parentheses around CONDITION:

 void main() { if(1 #define else ) printf("Hello "); else printf("World"); } 
+20
source
 CONDITION = printf("Hello") == 0; 
+3
source

Here is another approach. This is not as good as fork in that it only works half the time (therefore, does not completely solve the problem), but it is better that the message never changes.

 #include <stdio.h> int main() { if ( ftell( stdout ) % 2 || ( printf( " " ), main() ) ) printf( "Hello " ); else printf( "World\n" ); } 

He first queries stdout to find out how many were printed and the number of characters is odd. If so, it then prints one character to cancel parity and recursion. A recursive call sees an even number of characters and prints "hello" and returns 0. 0 sends the top call to else, printing "world".

The number of characters in the terminal must be odd for operation.

+3
source

Not quite what you requested, but the following will at least print the same result as when running both printf:

  if(printf("Hello ") & 0) printf("Hello "); else printf("World"); 
+2
source

Jumping straight from the cliff marked Potatoswatter , I suggest 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 had to declare main and give it a return value to close a couple of warnings. Perhaps even something suitable evil is defined in stdio.h, so we do not need to declare errno .

+2
source
 #include <stdio.h> main() { if (printf("Hello "),0) printf("Hello "); else printf("World"); return 0; } 
0
source

All Articles