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

后端 未结 30 2722
旧时难觅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:01

    Buckle your seatbelts:

    #include <stdio.h>
    #include <setjmp.h>
    
    int main()
    {
        jmp_buf env;
    
        if (!setjmp(env))
        {
            printf("if executed\n");
            longjmp(env, 1);
        }
        else
        {
            printf("else executed\n");
        }
    
        return 0;
    }
    

    Prints:

    if executed
    else executed
    

    Is this what you mean? I doubt it, but at least it's possible. Using fork you can do it also, but the branches will run in different processes.

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

    This could work:

    if (printf("Hello") - strlen("Hello"))
        printf("Hello")
    else
        printf("World")
    

    This snippet emphasizes the return value of printf: The number of characters printed.

    0 讨论(0)
  • 2020-12-05 03:02
    if  (true) printf ("Hello"); if (false)
        printf ("Hello");
    else
        printf("World");
    
    0 讨论(0)
  • 2020-12-05 03:05
    if(printf("Hello") == 1)
        printf("Hello")
    else
        printf("World")
    
    0 讨论(0)
  • 2020-12-05 03:05

    The condition to this question is:

     if(printf("hello")? 0 : 1) {   }
    
    0 讨论(0)
  • 2020-12-05 03:07

    The basic answer is that in the ordinary course of events you neither want to execute both the statements in the 'if' block and the 'else' block in a single pass through the code (why bother with the condition if you do) nor can you execute both sets of statements without jumping through grotesque hoops.

    Some grotesque hoops - evil code!

        if (condition == true)
        {
             ...stuff...
             goto Else;
        }
        else
        {
    Else:
            ...more stuff...
        }
    

    Of course, it is a plain abuse of (any) language because it is equivalent to:

        if (condition == true)
        {
             ...stuff...
        }
        ...more stuff...
    

    However, it might achieve what the question is asking. If you have to execute both blocks whether the condition is true or false, then things get a bit trickier.

        done_then = false;
        if (condition == true)
        {
    Then:
             ...stuff...
             done_then = true;
             goto Else;
        }
        else
        {
    Else:
            ...more stuff...
            if (!done_then) goto Then;
        }
    
    0 讨论(0)
提交回复
热议问题