Skip to main content
Be Bitwise

Conditionals: Making Decisions

Functions & Control Flow · Coding Fundamentals track

7 min read

In this module

Programs That Make Decisions

So far, every program we've talked about runs in a straight line — instruction after instruction, top to bottom. Real programs need to react to whatever's happening. Show an error message or a success screen? Charge tax or not? Retry or give up?

Conditionals are the mechanism that lets programs pick between paths of execution depending on whether something is true or false.

If Statements

The simplest conditional is the if statement. It evaluates a boolean expression and runs the attached block only if that expression is true.

text
if temperature > 100 {
print("Water is boiling!")
}

When temperature is 105, the message prints. When temperature is 80, the block gets skipped and execution rolls past the closing brace.

If / Else

A lot of the time you want one thing on a true result and something different on a false one. That's the job of else.

text
if age >= 18 {
print("You can vote.")
} else {
print("You cannot vote yet.")
}

Exactly one of these two blocks runs. Never both, never neither. The else block is the fallback when the condition comes out false.

Chaining Conditions with Else-If

More than two possibilities? Chain conditions together.

text
if score >= 90 {
grade = "A"
} else if score >= 80 {
grade = "B"
} else if score >= 70 {
grade = "C"
} else {
grade = "F"
}

Evaluation runs top to bottom. The first true condition wins, its block runs, and the rest of the chain gets skipped. If nothing matches, the else block fires.

Key Concept

Conditionals steer execution based on boolean expressions. An if/else chain evaluates top to bottom — first true condition wins, the rest get skipped. The trailing else is the catch-all when nothing matched.

Order matters, then. This C version has the chain upside down. Run it, work out why 95 comes back as a C, and reorder the conditions until every score gets the right grade.

Try itFix the order of the checks so 95 gets an A and 85 gets a B.
C (GCC 9.2.0)

Boolean Expressions and Operators

Conditions are built out of boolean expressions — expressions that evaluate to true or false. Stitch simple comparisons together with logical operators:

  • AND (written && or and): both sides must be true
  • OR (written || or or): at least one side must be true
  • NOT (written ! or not): flips true to false and vice versa
text
if age >= 18 and has_id {
print("Entry allowed")
}
if is_weekend or is_holiday {
print("No school today")
}
if not is_locked {
open_door()
}

Most languages also short-circuit these operators. If the left side of an AND is false, the whole thing is false, so the right side never runs; likewise for an OR whose left side is true. Programmers lean on that to guard risky checks:

Try itSwap the two sides of && so strcmp runs first, then run it again: the NULL user now crashes the whole program.
C (GCC 9.2.0)

These operators map straight onto the logic gates you've already met. At the hardware level, the CPU is evaluating these expressions through the same AND, OR, and NOT gates.

Switch / Match Statements

When you're checking one value against a pile of possibilities, some languages give you a switch or match statement — usually nicer than a long if/else chain.

text
switch day_of_week {
case "Monday":
print("Start of the work week")
case "Friday":
print("Almost the weekend")
case "Saturday", "Sunday":
print("Weekend!")
default:
print("Midweek")
}

It's functionally the same as the if/else chain, just easier on the eyes when you've got many specific values to check.

How the CPU Handles Branches

At the machine level, conditionals turn into branch instructions. The CPU runs a comparison ("is register A greater than register B?"), flips condition flags, and then either rolls forward to the next instruction or jumps to a different address.

asm
CMP R1, R2 ; compare R1 and R2
BGT label_true ; branch to label_true if R1 > R2
; ... else code runs here ...
JMP label_end
label_true:
; ... if-true code runs here ...
label_end:

Here's a real if/else in C next to x86-64 assembly for it. The assembly is hand-written in the style of unoptimised compiler output, with a arriving in edi and b in esi. Click a line on either side to see its partner.

if/else becomes compare and jump

x86-64
C Source
1int max(int a, int b) {
2 if (a > b)
3 return a;
4 else
5 return b;
6}
Assembly
1max:
2 cmp edi, esi ; compare a with b
3 jle .else ; a <= b: skip the if-block
4 mov eax, edi ; return value = a
5 ret
6.else:
7 mov eax, esi ; return value = b
8 ret

Hover over code lines or mapping badges to see correspondences

Look at the jump. The source says a > b, but the assembly tests the opposite, jle (jump if less or equal), because its job is to skip the if-block when the condition fails. Compilers flip conditions like this all the time, so expect it when you read disassembly. With optimisation on, a compiler might drop the jump altogether and use a conditional move (cmovge) instead.

Modern CPUs use branch prediction to guess which path a conditional will take before it's actually evaluated. Right guess, execution stays at full speed. Wrong guess, the CPU throws away its speculative work and rewinds — a real pipeline stall. That's why certain loop and conditional patterns have measurable performance impact even when they look identical in source.

Nesting and Complexity

Conditionals can nest inside each other, but deep nesting wrecks readability fast. Seasoned programmers tend to flatten deeply nested conditionals with early returns, guard clauses, or by carving the logic out into smaller functions.

text
// Deeply nested - hard to read
if is_valid {
if has_permission {
if not is_expired {
process()
}
}
}
// Flattened with early returns - easier to follow
if not is_valid { return }
if not has_permission { return }
if is_expired { return }
process()

Both versions do the same thing. The second is dramatically easier for humans. Control flow is about more than getting the computer to do what you meant — it's about making sure the next person reading the code can tell what you meant too.