In if (x), when is the condition true?
C treats every non-zero value as true and 0 as false. So if (-3) runs its body, and if (p) tests a pointer for NULL.
Control Instructions · Exercise 1 of 4
Twelve multiple-choice questions on if-else, switch, fall-through, short-circuit evaluation, the conditional operator, goto and the C23 changes. Pick an option to check your answer instantly.
In if (x), when is the condition true?
C treats every non-zero value as true and 0 as false. So if (-3) runs its body, and if (p) tests a pointer for NULL.
What does if (x = 5) { … } do?
= is assignment; its value is the value assigned (5), which is true. Compilers warn ("using the result of an assignment as a condition"). Use == to compare.
In if (a) if (b) s1; else s2; (no braces), which if does the else belong to?
An else always pairs with the closest preceding if that has no else yet. Indentation has no meaning to the compiler; add braces to say what you mean.
Which of these cannot be the controlling expression of a switch?
A switch needs an integer type. Floating-point values are not allowed (exact comparison of doubles would be unreliable anyway), and neither are strings.
Which statement about case labels is true?
Each label must be known at compile time (a literal, character constant, enum constant or macro) and no two may be equal. Their order is free.
A matching case has no break. What happens after its statements run?
Case labels are only entry points. Without break control falls through to whatever follows, until a break or the end of the switch.
Which is true about default in a switch?
default is optional and may be placed anywhere. It is chosen only if no case matches – but if it has no break, control falls through into the cases written after it.
In if (n != 0 && total / n > 5), what happens when n is 0?
&& evaluates left to right and stops when the result is known: with n == 0 the left side is false, so the division never happens. This is how guards are written in C.
What is the type of the expression flag ? 1 : 2.0?
The conditional operator has one type, worked out at compile time from both branches with the usual arithmetic conversions: int and double give double. So even when flag is true the result is 1.0.
Which use of goto is invalid?
A VLA's size is set when its declaration runs, so the language forbids jumping past it into its scope. Jumps must also stay inside the same function.
Timed online tests with instant scores and explanations.