What's the “condition” in C interview test?

后端 未结 30 2723
旧时难觅i
旧时难觅i 2020-12-05 02:37

Would it be possible to print Hello twice using single condition?

if  \"condition\"
  printf (\"Hello\");
else
  printf(\"World\");         


        
相关标签:
30条回答
  • 2020-12-05 03:15

    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

    0 讨论(0)
  • 2020-12-05 03:17
    "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. :-)

    0 讨论(0)
  • 2020-12-05 03:17

    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");
    
    0 讨论(0)
  • 2020-12-05 03:17

    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.

    0 讨论(0)
  • 2020-12-05 03:18
    if (printf("Hello") < 1)
        printf("Hello");
    else
        printf("World");
    
    0 讨论(0)
  • 2020-12-05 03:19

    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... :)

    0 讨论(0)
提交回复
热议问题