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

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

    Cheeting with an empty else statement:

    if (condition)
        // do if stuff
    else;
        // do else stuff
    

    If you don't like the fact that else; is actually an empty else statement try this:

    for (int ii=0; ii<2; ii++)
    {
        if (condition && !ii)
            // do if stuff
        else
        {
            // do else stuff
            break;
        }
    }
    
    0 讨论(0)
  • 2020-12-05 03:08

    No love for exit?

    if(printf("HelloWorld"), exit(0), "ByeBye") 
        printf ("Hello");
    else
        printf ("World");
    
    0 讨论(0)
  • 2020-12-05 03:08

    Solution 1:

    int main(int argc, char* argv[])
    {   
        if( argc == 2 || main( 2, NULL ) )
        {
            printf("Hello ");   
        }
        else
        {
            printf("World\n");
        }
        return 0;
    }
    

    Solution 2 (Only for Unix and Linux):

    int main(int argc, char* argv[])
    {   
        if( !fork() )
        {
            printf("Hello ");   
        }
        else
        {
            printf("World\n");
        }
        return 0;
    }
    
    0 讨论(0)
  • 2020-12-05 03:09
    #define CONDITION (0) if (0) {} else
    

    or some such.

    If you see such a question on an interview, run away as fast as you can! The team that asks such questions is bound to be unhealthy.

    Edit - I forgot to clarify - this relies on "else" being matched with closest open "if", and on the fact that it's written as "if CONDITION" rather than if (CONDITION) - parenthesis would make the puzzle unsolvable.

    0 讨论(0)
  • 2020-12-05 03:09
    int main()
    {
        runIfElse(true);
        runIfElse(false);
    
        return 0;
    }
    
    void runIfElse(bool p)
    {
        if(p)
        {
         // do if
        }
        else
        {
         // do else
        }
    }
    
    0 讨论(0)
  • 2020-12-05 03:10

    Comment the "else" ;)

    if(foo)
    {
        bar();
    }
    //else
    {
        baz();
    }
    
    0 讨论(0)
提交回复
热议问题