What are the values of !0 and !5?
! gives 1 for a zero operand and 0 for any non-zero operand. The result is an int.
Decision Making · Exercise 1 of 4
Twelve multiple-choice questions on truth values, De Morgan's laws, range checks, guard order, comparing strings and doubles, and choosing between if, switch and tables. Pick an option to check your answer instantly.
What are the values of !0 and !5?
! gives 1 for a zero operand and 0 for any non-zero operand. The result is an int.
Which expression is equivalent to !(a && b)?
"Not both" means "at least one is false": negate each part and switch && to ||. Likewise !(a || b) is !a && !b.
Which condition is true exactly when x is between 10 and 20, inclusive?
Both bounds must hold, so join them with &&. The chained form is parsed as (10 <= x) <= 20 (always true), and the || version is true for every x.
p may be a null pointer. Which condition is safe?
&& evaluates left to right and stops at the first false operand, so the NULL test must come first. The single & evaluates both sides and does not protect anything.
Which condition checks whether the string role equals "admin"?
== compares addresses. strcmp() returns 0 when the strings are equal – so the bare call is true when they differ, a classic mistake.
Two computed doubles should be treated as equal. Which condition is appropriate?
Rounding errors make exact equality unreliable (0.1 * 3 != 0.3). Compare the difference with a tolerance – relative to the values' size for large numbers.
Without any else, which is equivalent to if (a) { if (b) { work(); } }?
The inner block runs only when both conditions are true, and b is tested only when a is true – exactly the short-circuit behaviour of &&.
For a pointer p, what does if (p) test?
A pointer used as a condition is compared with the null pointer: if (p) means if (p != NULL). It says nothing about the value p points to.
What does bool ok = 42; store?
Converting any scalar to bool yields 0 if it compares equal to 0 and 1 otherwise. This differs from converting to an int type, where 0.5 would become 0 but as a bool it becomes 1.
How do you test that exactly one of two int flags a and b (which may hold any value) is true?
C has no logical XOR. !a and !b are 0 or 1, so !a != !b is true exactly when one flag is set. a ^ b fails for a = 2, b = 4 (result 6, "true", though both are set), and a != b fails for 2 and 4 too.
Timed online tests with instant scores and explanations.