ExamVeda
Login
Home
This question belongs to C Program Control Structures
Control Structures
?

What will be the output of the following C code?
#include <stdio.h>
int main()
{
    switch (printf("Do"))
    {
       case 1:
          printf("First\n");
          break;
       case 2:
          printf("Second\n");
          break;
       default:
          printf("Default\n");
          break;
    }
}

Answer & Solution
Correct Answer: Option C
In this code, the switch statement is evaluating the result of the printf("Do") function call. The printf() function returns the number of characters printed.

When printf("Do") is executed, it prints "Do" to the standard output and returns the number of characters printed, which is 2.

So, the switch statement evaluates the value 2.

Since there is a case 2 in the switch statement, it will execute the corresponding code block, which prints "Second" to the standard output.

Therefore, the correct output of the code will be DoSecond. So, the correct answer is Option C: DoSecond.
Examveda
Question posted by Examveda
Community

Join the Discussion

1 Comment
Riddhi Mukhtyar
Riddhi Mukhtyar 2 years ago
I believe there's a misunderstanding. Let's reassess the code snippet:


int main()
{
switch (printf("Do"))
{
case 1:
printf("Firstn");
break;
case 2:
printf("Secondn");
break;
default:
printf("Defaultn");
break;
}
}
```

The `printf` function inside the `switch` statement prints "Do" and returns the number of characters printed, which is 2. Therefore, the `switch` statement evaluates to `switch(2)`.

However, there's no `case 2` in the `switch` statement, so the `default` case will be executed, printing "Default".

Therefore, the output should be:

D. DoDefault

This aligns with the analysis provided earlier. So, the correct answer should be Option D, "DoDefault."