For starters, let's consider what the function printf
returns. From the C Standard
3 The printf
function returns the number of characters transmitted, or
a negative value if an output or encoding error occurred.
So the condition of this if
statement
if(printf("Hello"))
evaluates to true because printf()
returns a non-zero value.
Then this switch
statement
switch(printf("World"))
is evaluated.
Now let's consider how the switch
statement works. From the C Standard
4 A switch
statement causes control to jump to, into, or past the
statement that is the switch body, depending on the value of a
controlling expression, and on the presence of a default label and the
values of any case labels on or in the switch body. A case or default
label is accessible only within the closest enclosing switch
statement.
As the body statement of the switch
statement does not have a label (including the default label) then the control is passed past the body statement. That is, the while
statement (that is a body statement of the switch
statement) is not executed.
If you want to get the expected by you result then for example insert the label default
.
#include <stdio.h>
int main()
{
if(printf("Hello"))
switch(printf("World"))
default: while(printf("There"))
{
return 0;
}
}
In this case the program output is
HelloWorldThere
Or use a null-statement as the body statement of the switch statement.
#include <stdio.h>
int main()
{
if(printf("Hello"))
switch(printf("World")); // <==
while(printf("There"))
{
return 0;
}
}
printf
returns.switch
statement too ... Your code is totally a non-sense.switch
: "If expression evaluates to a value that doesn't match any of the case: labels, and the default: label is not present, none of the switch body is executed." -- nocase
labels, so nothing to match the expression, and nodefault
label, so nothing happens.