Conditions: if-else and switch

Video lessonComing soon

1 Code that makes a choice

Many problems need code that behaves differently for different inputs. A cinema charges a child less than an adult. A calculator adds for + and multiplies for *.

A condition is a question about a value with a Yes or No answer, such as "is the age under 13?". The program asks it and runs one set of steps or another. The flowchart lesson drew this as a diamond. In code, it is an if statement or a switch.

Our running example is the price of a cinema ticket:

AgeTicketPrice
Under 13Child80
13 to 59Adult200
60 and overSenior120
Child, 80Adult, 200Senior, 12001360100+
Every age falls in exactly one range

A first try at these rules often charges a 60-year-old or a child the adult price. Both mistakes come from the order and the edges of the checks.

2 Comparison and logic

A condition is built from comparison operators. Each one compares two values and gives true or false. Here they are for age = 13:

OperatorMeansExampleResult
==equal toage == 13true
!=not equal toage != 13false
<less thanage < 13false
<=less than or equal toage <= 13true
>greater thanage > 13false
>=greater than or equal toage >= 13true

< and <= differ only at exactly 13. Most condition bugs live at a value like that.

Comparison uses two equals signs. A single = puts a value into a variable. In JavaScript we write ===, because == converts types first and calls "13" == 13 true.

Logical operators join conditions:

OperatorC++, Java, JavaScript, Go, Rust, C#PythonTrue when
and&&andboth sides are true
or||orat least one side is true
not!notthe condition is false

So an adult is age >= 13 && age <= 59, and both parts must hold.

Both and and or stop early. When the left side of an and is false, the right side never runs. This lets a safe check guard a risky one:

if b != 0 and a % b == 0
    print "b divides a"

For a = 7, b = 0, the code never calculates 7 % 0. With the sides swapped, 7 % 0 runs first and crashes with a Runtime Error. So the guard goes on the left.

3 if, else if, else

An if runs its block only when its condition is true. An else runs when it is false. For more than two paths, we put else if between them. This is an if-else chain:

if age < 13
    price = 80
else if age < 60
    price = 200
else
    price = 120
StartRead ageage < 13?price = 80age < 60?price = 200price = 120Print priceEndNoNoYesYes
The first Yes decides the price; the rest are skipped

The chain asks its questions from the top. It runs the block of the first true one and skips the rest. When none is true, the else runs. So exactly one block runs.

Here is the chain for five ages. A dash means the question is never asked:

ageage < 13?age < 60?price
8Yes—80
13NoYes200
45NoYes200
60NoNo120
72NoNo120

The second check needs no age >= 13. The code reaches it only when age < 13 was false.

Python writes else if as elif. In Rust, an if gives back a value, so the chain goes straight into price.

4 Order and boundaries

The chain stops at the first true check, so the order matters. Here are the first two checks swapped:

if age < 60
    price = 200
else if age < 13
    price = 80
else
    price = 120

For age 8, age < 60 is true first, so a child pays 200. The child check never runs. When one range sits inside another, the narrow one goes first. The safe habit is to walk the number line in one direction, from the youngest up or from the oldest down.

The edges matter too. "60 and over" is age >= 60, not age > 60. With >, age 72 still gets 120, and only age 60 gets the wrong price. So for each boundary in the statement, we test the value on each side of it:

ageWhy we test itRight price
0the smallest age80
12the last child age80
13the first adult age200
59the last adult age200
60the first senior age120

The words decide between < and <=. "Under 13" is age < 13. "60 and over" and "at least 60" are age >= 60.

5 switch: one value, many cases

Some choices compare one value with a list of exact values. Turning a day number, 1 for Monday up to 7 for Sunday, into its name is one. A chain would repeat day == seven times. A switch names the value once and lists the cases:

  • switch (day) names the value to compare.
  • case 1: marks where to start when the value is 1.
  • break leaves the switch.
  • default: runs when no case matches, like the else of a chain.

Python and Rust write a switch as match, with _ as the default.

C++

A break in every case. Without it, the next case runs as well.

No strings. A switch works only on whole numbers and characters.

A break in every case. Without it, the next case runs as well.

A break in every case. Without it, the next case runs as well.

A break in every case. Without it, the code does not compile.

No break needed. Go ends each case on its own.

Every value covered. A match without the _ line is a Compile Error.

case _ is the default. Without it, a value that matches no case does nothing.

6 Fallthrough

A case label is only a starting point, and break is what stops the code there. Without break, the code runs on into the next case's lines. This is fallthrough. Here is the switch with every break missing:

switch day
    case 1: name = "Monday"
    case 2: name = "Tuesday"
    case 3: name = "Wednesday"
    case 4: name = "Thursday"
    case 5: name = "Friday"
    case 6: name = "Saturday"
    case 7: name = "Sunday"
    default: name = "Invalid"
return name

A dry run for day = 6:

StepLine that runsname
1case 6 matchesSaturday
2falls into case 7Sunday
3falls into defaultInvalid

Every day ends at default and returns "Invalid", and nothing warns us.

Fallthrough helps when several values share one answer, such as 6 and 7 for the weekend:

Language6 and 7 share one case
C++, Java, JavaScript, C#case 6: case 7:
Gocase 6, 7:
Pythoncase 6 | 7:
Rust6 | 7 =>

7 Mistakes to watch for

Each mistake below has an input that exposes it:

  • = instead of ==. In C++ and JavaScript, if (day = 7) sets day to 7 and counts as true, so day = 3 gives "Sunday". The other languages refuse to run it.
  • if instead of else if. A separate if is asked every time. For age 8, age < 13 sets 80, and then age < 60 replaces it with 200.
  • The wide check first. With age < 60 above age < 13, age 8 pays the adult price.
  • > instead of >=. For "60 and over", age > 60 gives age 60 the adult price.
  • A missing break. For day = 6, the code falls into default and returns "Invalid".

Bands of numbers, such as ages or marks, call for an if-else chain in order along the number line. A short list of exact values, such as days or operators, reads better as a switch.

The habit to keep: for every boundary in the statement, test the value just below it and the value on it. Most condition bugs sit at exactly those two inputs.

Practice it

Finished this lesson?

Mark it read and it is ticked on the roadmap and in the list.

Article

Send feedback

Thank you for helping. We read every report and fix what is wrong.

How do you feel about oneby7?

Sign in to oneby7

Keep your progress, your streak and your code, on any device.

New here? This creates your account too.