90 דק׳

switch ואופרטור התנאי

switch קופץ ל־case המתאים וממשיך עד break; cases מקובצים; למה switch לא בודק טווחים; איך בוחרים מבנה; ו־?: שמחשב רק את הערך שנבחר.

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

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

switch: choose by one exact value

The chamber controller has three modes, and each mode has its own temperature limit: N (normal) 80 °C, T 70 °C, S 60 °C. One value (mode) is compared with a few exact constants. That is the job of switch.

switch (mode) {
    case 'N':
        limit = 80;
        break;
    case 'T':
        limit = 70;
        break;
    case 'S':
        limit = 60;
        break;
    default:
        limit = -1;
}

What the computer does with mode = 'T':

  1. It evaluates mode once.
  2. It jumps straight to the label case 'T':. It does not test 'N' first the way an else-if chain would.
  3. It runs limit = 70;.
  4. break leaves the switch. The program continues after the closing }.

If no case matches (mode = 'X'), C jumps to default. A switch without a default simply does nothing for an unexpected value, and limit keeps whatever it had: often an uninitialised variable. Every switch should have a default.

A switch is a good fit when:

  • there is one value to test,
  • that value is an int or a char (a char is a small integer in C, so 'N' works as a label),
  • it is compared with constant labels,
  • there are several named choices.
Click a mode to see where the switch jumps. 'X' has no case, so default runs.לפתיחה במסך מלא

Fall-through: a case is an entry point

A case label is only a place to enter. C does not stop at the next label. It keeps running down until it meets a break or the end of the switch. This is called fall-through.

switch (code) {
    case 1: printf("A");
    case 2: printf("B");
    case 3: printf("C"); break;
    default: printf("D");
}
codeenters atrunsoutput
1case 1A, B, C, then breakABC
2case 2B, C, then breakBC
3case 3C, then breakC
4defaultD, end of switchD
Pick a code and watch the arrow enter at its label and run down until the break.לפתיחה במסך מלא

Grouped cases: fall-through on purpose

Sometimes several values should do the same thing. Then fall-through is useful:

switch (command) {
    case 'R':
    case 'r':
        printf("RESET");
        break;
    case 'S':
    case 's':
        printf("STATUS");
        break;
    default:
        printf("INVALID");
}

With command = 'R', C enters at case 'R':. That label has no statements, so C runs on into the code under case 'r':, prints RESET, and leaves at break. Both letters share one printf. Writing printf("RESET") twice would work too, but then there are two places to change when the message changes.

When the reason for a fall-through is not obvious, write a short comment such as /* falls through on purpose */.

switch cannot test a range

This looks tempting, and it does not compile:

/* Invalid idea */
switch (temperature) {
    case temperature >= 80:
        state = 3;
        break;
}
error C2051: case expression not constant

A case label must be an integer constant: a number such as 80 or a character such as 'N', known when the program is compiled. A comparison that depends on a variable is not allowed.

  • Exact values → switch.
  • Ranges → if / else if.
  • Both → mix them: a switch on the mode to pick the limit, then an if chain on the temperature. Lesson 3 builds exactly that.

Which structure fits?

SituationPreferWhy
mode is 'N', 'T' or 'S'switchone value, exact constants
temperature below 60, 60 to 79, 80 or moreelse ifranges need < and >=
temperature matters only if the battery is finenested ifthe second question depends on the first
pick the larger of two numbers?:one small value from two

Two structures can often both produce the right output. Choose the one that shows the shape of the specification: someone reading the code should see at once "these are exact choices" or "these are ranges".

The conditional operator ?:

The conditional operator (אופרטור התנאי) chooses one of two values:

result = condition ? value_if_true : value_if_false;

Read it as: "if the condition is true, this value, otherwise that value".

int larger = (a > b) ? a : b;
char lamp = alarm ? 'R' : 'G';

With a = 5, b = 8: (a > b) is false, so larger gets b, which is 8. With alarm = 1: the lamp is 'R'.

C evaluates the condition first and then only the chosen value. The other value is never evaluated, just like the right side of a short-circuited &&. So this is safe even when divisor is 0:

int value = (divisor != 0) ? total / divisor : -1;
The value that is not chosen is greyed out: C never evaluates it.לפתיחה במסך מלא

Clear beats clever

?: is good for one short choice. Nesting it is legal, but hard to read:

state = battery < 15 ? 3 :
        temperature >= 80 ? 3 :
        temperature >= 60 ? 2 : 1;

The same decision as an if chain is easy to check line by line:

if (battery < 15 || temperature >= 80)
    state = 3;
else if (temperature >= 60)
    state = 2;
else
    state = 1;

Use ?: when both results fit in one short thought.

Precedence: add the parentheses

What prints?

int a = 5;
int b = 8;
int result;
result = a > b ? a : b + 10;
printf("%d", result);
18

?: has very low precedence, so C reads the line as result = (a > b) ? a : (b + 10);. The condition 5 > 8 is false, so the second value is chosen, and the second value is the whole b + 10, which is 18.

Do not rely on the reader knowing the precedence table. Write the parentheses yourself: result = (a > b) ? a : (b + 10);.

Exit check

Answer without compiling:

int x = 2;
int y = 5;
int z = (x > y) ? x : y;
switch (z) {
    case 5: printf("A");
    case 6: printf("B"); break;
    default: printf("C");
}
AB

z gets the larger value, 5. C enters at case 5, prints A, finds no break, falls into case 6, prints B and stops at its break. To print only A, add break; after printf("A");.

Key words

EnglishHebrewMeaning
switchמשפט switchchooses a path by one exact value
case labelתווית casean entry point inside the switch
breakיציאה מה־switchleaves the switch at once
defaultברירת מחדלruns when no case matches
fall-throughהמשך ל־case הבאrunning on into the next case
integer constantקבוע שלםwhat a case label must be
conditional operator ?:אופרטור התנאיchooses one of two values
precedenceקדימות אופרטוריםwhich operator groups first

Practice

More questions, with answers, on the practice page: challenges 3, 4, 5, 10 and 11 and problems 11-24 fit this lesson.