90 דק׳

החלטות מקוננות ובדיקות גבול

הערכה מקוצרת, if מקונן, ה־else התלוי, סדר ענפים, טבלאות החלטה, ובדיקות מתחת, על ומעל כל גבול.

למצגתלקריאה באתרבאנגלית בלבד

השיעור הזה כתוב באנגלית בלבד.

Incident 27B: a program that passed its tests

A test chamber controller reads three inputs: the temperature in °C, the battery charge from 0 to 100, and an operating mode (N, T or S). From these it chooses one state: RUN, WARN or SHUTDOWN.

The failure report says: at exactly 80 °C the software reported WARN. The safety specification requires SHUTDOWN.

The code compiled. The usual test values passed. And it still chose the wrong safety state at one temperature. This lesson is about two skills that would have caught it:

  • writing decisions that depend on each other correctly (nested decisions, branch order), and
  • choosing tests that prove a decision is right (boundary tests).

The same controller runs through the whole unit.

Warm-up: what does C check, and what does it skip?

Answer without running the code.

int x = 10;
int y = 20;
 
if (x < 12 && y == 20)
    printf("A");
else if (x < 2)
    printf("B");
else
    printf("C");
A

x < 12 is true and y == 20 is true, so the first condition is true and A prints. An else-if chain stops at the first true condition: x < 2 is never evaluated.

To make B print, the first condition must be false and x < 2 must be true. For example x = 1, y = 19. (A common wrong answer is x = 10, y = 19: the first condition becomes false, but 10 < 2 is false too, so C prints.)

&& and || stop early

C evaluates A && B and A || B from left to right, and stops as soon as it knows the answer. This is called short-circuit evaluation (הערכה מקוצרת).

ABA && B
falsenot checkedfalse
truefalsefalse
truetruetrue
ABA || B
falsefalsefalse
falsetruetrue
truenot checkedtrue
  • && stops at the first false: if A is false, the whole thing is false whatever B is.
  • || stops at the first true: if A is true, the whole thing is true whatever B is.

On the controller, with if (battery < 15 || temperature >= 80): when the battery is 10, the left side is true, and C never reads the temperature. When the battery is 50, the left side is false, so C must check the temperature.

Two inputs, one condition. With battery 10 the right side is greyed out: C never evaluates it.לפתיחה במסך מלא

This matters when the right side is only safe after the left side passed, for example divisor != 0 && total / divisor > 5: the division runs only when the divisor is not zero.

Weak tests and strong tests

Here is a controller with one wrong character. The specification says "80 °C or more gives SHUTDOWN", the code says >:

if (temperature > 80)
    printf("SHUTDOWN");
else
    printf("RUN");

Test it with 20, 50 and 90. All three give the right answer. The tests passed, and the bug is still there, because none of them is at 80.

Now test with 79, 80 and 81: just below the boundary, exactly at it, and just above it. 80 prints RUN instead of SHUTDOWN. The bug is found.

A boundary (גבול) is the value where the result changes. A boundary test (בדיקת גבול) is a test just below, exactly at, or just above a boundary. Every one of the three values has a purpose:

ValuePurposeCatches
79below the boundarya boundary that is too low (>= 79)
80at the boundary> written instead of >=
81above the boundarya boundary that is too high (> 81)
Move the slider and look for the input that fails. Only one value between 60 and 100 does.לפתיחה במסך מלא

Nested if: a question that depends on another

Some questions matter only after another one has been answered. "Is it too hot?" matters only if the battery is not already critical. That dependency is the reason to put one if inside another: a nested if (if מקונן).

if (battery < 15) {
    state = 3;   /* SHUTDOWN */
} else {
    if (temperature >= 80) {
        state = 3;   /* SHUTDOWN */
    } else {
        state = 1;   /* RUN */
    }
}

Read it as questions:

  1. Is the battery critical? If yes, SHUTDOWN, and the temperature is never checked.
  2. Only if not: is the temperature dangerous?

Exactly one state is assigned on every path. Trace two cases:

batterytemperatureconditions checkedstate
102010 < 15 true3
508050 < 15 false, 80 >= 80 true3

Here is the same decision as a complete program you can run in Visual Studio (Ctrl+F5):

#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
 
int main(void)
{
    int battery, temperature;
 
    printf("Battery and temperature: ");
    scanf("%d %d", &battery, &temperature);
 
    if (battery < 15) {
        printf("SHUTDOWN\n");
    } else {
        if (temperature >= 80) {
            printf("SHUTDOWN\n");
        } else {
            printf("RUN\n");
        }
    }
    return 0;
}
Battery and temperature: 50 80
SHUTDOWN

The dangling else

What prints when enabled is 0 and temperature is 20?

if (enabled)
    if (temperature >= 80)
        printf("SHUTDOWN");
else
    printf("RUN");

The indentation suggests that else belongs to if (enabled), so RUN would print. But C ignores indentation. The rule is: an else belongs to the nearest if before it that has no else yet. Here that is if (temperature >= 80). This is called the dangling else (else תלוי).

So C reads the code like this:

if (enabled) {
    if (temperature >= 80) {
        printf("SHUTDOWN");
    } else {
        printf("RUN");
    }
}

enabled is 0, the outer if is false, and nothing prints.

If RUN should belong to the outer if, braces must say so:

if (enabled) {
    if (temperature >= 80) {
        printf("SHUTDOWN");
    }
} else {
    printf("RUN");
}

Branch order: a branch that can never run

if (temperature >= 60)
    printf("WARN");
else if (temperature >= 80)
    printf("SHUTDOWN");
else
    printf("RUN");

Try 95 °C: 95 >= 60 is true, WARN prints, and the chain ends. The SHUTDOWN branch is legal C, it compiles, and it can never run: every temperature that is >= 80 is also >= 60, so the first test always catches it first. A test at one value is not even needed to prove this; the logic proves it.

In an else-if chain, the first true condition wins. When ranges overlap, test the most restrictive range first:

if (temperature >= 80)
    printf("SHUTDOWN");
else if (temperature >= 60)
    printf("WARN");
else
    printf("RUN");

Now each range has its own branch: below 60 RUN, 60 to 79 WARN, 80 and above SHUTDOWN.

The number line shows why: the range >= 60 already covers everything >= 80.לפתיחה במסך מלא

Do not memorise "largest number first": with < comparisons the right order is the other way round. Think in ranges, as in the next section.

Decision table before code

A decision table (טבלת החלטה) lists every range of the inputs and the result for each. Write it before the code:

batterytemperatureresult
below 15anySHUTDOWN
15 or more80 or moreSHUTDOWN
15 or more60 to 79WARN
15 or morebelow 60RUN

"Any" means the temperature does not need to be checked at all in that row. Check the table with three questions:

  1. Is every input covered? Yes: every battery value falls in one battery range, and every temperature in one temperature range.
  2. Can two rows match the same input? No: the battery splits at 15, the temperature at 60 and 80, and the ranges do not overlap.
  3. Where are the boundaries? At 15, 60 and 80. Those are the values to test.

Boundary tests: below, at, above

From the table, a test plan with a purpose for every test:

Purposebatterytemperatureexpected
below the battery boundary1420SHUTDOWN
at the battery boundary1520RUN
below the heat boundary5079WARN
at the heat boundary5080SHUTDOWN
above the heat boundary5081SHUTDOWN
below the warn boundary5059RUN
at the warn boundary5060WARN
above the warn boundary5061WARN

One test per range is not enough: code usually fails exactly at a boundary, as the incident showed.

Trace challenge: two ifs, one final state

int state = 0;
if (battery < 15)
    state = 3;
if (temperature >= 80)
    state = 3;
else if (temperature >= 60)
    state = 2;
else
    state = 1;
printf("%d", state);
batterytemperatureoutput
10201
10702
50803

With battery 10 and temperature 20: the first if sets state = 3. Then the second if is a new decision, not part of the first. Its chain runs too: 20 >= 80 false, 20 >= 60 false, so state = 1 overwrites the 3. The program prints 1, although a critical battery must give SHUTDOWN (3).

Watch the state box: 0, then 3, then 1. The old values stay crossed out.לפתיחה במסך מלא

The repair is one word, else, which joins the two decisions into one chain:

int state = 0;
if (battery < 15)
    state = 3;
else if (temperature >= 80)
    state = 3;
else if (temperature >= 60)
    state = 2;
else
    state = 1;
printf("%d", state);

A repair is proved by a test that failed before and passes after: battery 10, temperature 20 must print 3. The old code printed 1.

Key words

EnglishHebrewMeaning
nested ifif מקונןan if inside another if
short-circuit evaluationהערכה מקוצרת&& and || stop once the answer is known
dangling elseelse תלויan else belongs to the nearest if without an else
branchענףone path through an if chain
unreachable branchענף שלא מגיעים אליוlegal code that can never run
decision tableטבלת החלטהevery input range with its result
boundaryגבולthe value where the result changes
boundary testבדיקת גבולa test below, at or above a boundary
test caseמקרה בדיקהan input with its expected output
expected / observedצפוי / בפועלwhat the specification says / what the program did

Practice

More questions, with answers, on the practice page: challenges 1, 2, 6, 7 and 8 and problems 01-10 fit this lesson.