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

后端 未结 30 2720
旧时难觅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 02:52

    The if statement executes one or the other of the controlled statements (both printf in your example). No matter what you use for condition, that snippet will either print "Hello", or "World", but never both.

    Edit: Okay, so it's a trick question and you can put whatever you like in the condition (including a call to an entire other function that does anything you want). But that's hardly interesting. I can't believe I got downmodded for giving a correct answer.

    0 讨论(0)
  • 2020-12-05 02:53
    if (printf("hello") & 0)
    {
    printf("hello");
    }
    else
    {
    printf("world");
    

    No need to bother about the return value of printf.

    0 讨论(0)
  • 2020-12-05 02:54

    Two possible Solutions without using printf statements :-

    First :-

    #include <stdio.h>
    
    int
    main(void)
    {
      if (!stdin || (stdin = 0, main()))
        printf("hello");
      else
        printf("world");
      return 0;
    }
    

    Second

    #include<stdio.h>
    void main()
    {
    if (1
    #define else if (1) 
    )
    { 
      printf("hello"); 
    } 
    else
     { 
        printf("world"); 
    }
    }
    

    Reference :- Link1 , Link2

    0 讨论(0)
  • 2020-12-05 02:56

    If it is on Unix:

    if  (fork())
        printf ("Hello");
    else
        printf("World");
    

    Ofcoures that doesn't guarantee the order 0f the prints

    0 讨论(0)
  • 2020-12-05 02:57

    use a goto, one of the single most underused keywords of our day

    0 讨论(0)
  • 2020-12-05 02:59

    So... you want to execute the code inside the if block... and the code inside of the else block... of the same if/else statement? Then... you should get rid of the else and stick taht code in the if.

    if something
      do_this
      do_that
    end
    

    The else statement is designed to execute only if the if statement is not executed and vice-versa, that is the whole point. This is an odd question...

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