Programming Search⌘K

Conceptcore

Conditional

Also called conditional, conditional statement, if statement, if-then-else, if else, else if, elif, conditional expression, ternary operator, conditional operator, selection statement, branch, dangling else, guard clause.

A conditional runs one piece of code when a condition is true and, optionally, another when it is false. The if statement and the conditional expression are its two main forms.

Applies to
core-languages

Idea

A program often has to do different things in different cases: charge more for a heavy parcel, show an error for bad input, skip a step when there is nothing to do. A conditional tests a condition and runs one piece of code when it is true and, optionally, another piece when it is false. Wikipedia says that "a conditional statement directs program control flow based on the value of a condition"1.

def shipping(weight_kg, express):
    # The tests run in order, and only the first true branch runs.
    if weight_kg <= 0:
        raise ValueError("weight must be positive")
    elif weight_kg < 1:
        cost = 5
    elif weight_kg < 10:
        cost = 9
    else:
        cost = 20
    # An if with no else runs its body or does nothing.
    if express:
        cost *= 2
    return cost


for w, e in [(0.5, False), (3, True), (25, False)]:
    print(w, e, shipping(w, e))

# A conditional expression chooses between two values.
n = 4
print(n, "is", "even" if n % 2 == 0 else "odd")

# Only the chosen branch is evaluated, so 10 / d does not run when d is 0.
d = 0
print("undefined" if d == 0 else 10 / d)
Output
0.5 False 5
3 True 18
25 False 20
4 is even
undefined

The if, elif and else chain in shipping tests its conditions from top to bottom and runs only the first branch whose condition is true. The second if has no else, so it doubles the cost or does nothing. The conditional expression "even" if n % 2 == 0 else "odd" chooses between two values. In the last line, only the chosen operand is evaluated, so 10 / d never runs and there is no division by zero.

How it works

The if statement. Python says that "The if statement is used for conditional execution"2. It "selects exactly one of the suites by evaluating the expressions one by one until one is found to be true"2, and "If all expressions are false, the suite of the else clause, if present, is executed"2. The other languages state the same rule. In Java, "The if statement allows conditional execution of a statement or a conditional choice of two statements, executing one or the other but not both"3. In Go, "If" statements "specify the conditional execution of two branches according to the value of a boolean expression"4.

The condition. Java, C#, Go and Rust require a Boolean condition. In Rust, "Condition operands must be either an Expression with a boolean type or a conditional let match"5. Python, JavaScript, C and C++ accept other values and test their truth. MDN says that the if...else statement "executes a statement if a specified condition is truthy"6. In C, the branch runs when the expression is not zero.

Chains. else if is an if statement in the else branch of another, so a chain of tests is a nest of if statements written flat. Python, Bash and others have a keyword for it, such as elif. A switch or a match statement also chooses a branch, but it compares one value with many cases, and C# adds a case guard, a condition "after the when keyword"7.

Dangling else. In if (a) if (b) x(); else y();, the else could belong to either if. C and C++ give it to the inner one: "the else is associated with the closest if that does not yet have an associated else"8. Languages with required braces or with indentation, such as Go, Rust and Python, do not have this ambiguity.

Conditional expressions. "A conditional expression evaluates to a value without the side-effect of changing control flow"1. In C, Java, JavaScript and C#, it is the operator c ? a : b. In JavaScript it "is the only JavaScript operator that takes three operands"9. In Java, "The conditional operator ? : uses the boolean value of one expression to decide which of two other expressions should be evaluated"10. Python writes x if C else y, which "first evaluates the condition, C rather than x"11. In Rust, if itself is an expression, and "An if expression evaluates to the same value as the executed block"5. Go has no conditional expression, so a choice of value uses an if statement.

Compile-time conditionals. Some conditions are known before the program runs. C and C++ use #if in the preprocessor, and C++ has if constexpr, in which the branch that is not taken is a "discarded statement"8. Rust uses the cfg attribute.

In languages

LanguageVerdictNote
PythonNative
C++Native
JavaNative
CNative
C#Native
JavaScriptNative
TypeScriptNativeTypeScript has the if statement and the conditional operator of JavaScript, and the compiler narrows the type of a variable in each branch, for example after typeof x === "string". No example file exists.
GoNative
RustNative
KotlinNativeIn Kotlin, if is an expression, so it replaces the conditional operator, and when without an argument is a chain of conditions. A condition must be a Boolean. No example file exists because kotlinc is not installed.
SQLNativeThe CASE expression chooses a value with WHEN, THEN and ELSE, and WHERE and HAVING keep only the rows for which a condition is true. No example file exists.
BashNativeBash runs the branch of if, elif and else according to the exit status of a command, and [[ ]] and test give that status for comparisons. && and || run a command only when the previous one succeeds or fails. No example file exists.
PowerShellNativePowerShell has if, elseif and else, a switch statement with conditions, and a conditional operator with ? and :. It converts other values to bool in a condition. No example file exists because pwsh is not installed.
HTMLDoes not applyHTML has no conditionals. Scripts or a template language decide which content a page contains.
CSSIdiomThe rules @media, @supports and @container apply only when their condition is true.
Regular expressionsIdiomAlternation with | chooses between patterns, and some engines, such as PCRE and .NET, have conditionals that test whether a group matched.
Language Verdict Mechanism
Python native if, elif, else; x if c else y; truth values of all objects; match with guards
JavaScript native if, else; c ? a : b; truthy and falsy values; ?? and ?.
TypeScript native the conditionals of JavaScript; each branch narrows the types of variables
Java native if, else; c ? a : b; instanceof patterns; the condition must be boolean
Kotlin native if is an expression; when with conditions; no c ? a : b operator
C# native if, else; c ? a : b; is patterns with and, or and not; when guards
Go native if with a short statement; switch with no expression; no conditional operator
Rust native if is an expression; if let, let else and let chains
C native if, else; c ? a : b; any non-zero scalar is true; #if
C++ native the conditionals of C; if with an initializer; if constexpr; likely
Bash native if, elif, else, fi on the exit status of a command; [[ ]]; && and ||
PowerShell native if, elseif, else; c ? a : b in PowerShell 7; switch
SQL native CASE WHEN ... THEN ... ELSE ... END in expressions; WHERE filters rows by a condition
Regex idiom alternation with |; some engines have conditionals such as (?(1)a|b)
HTML n/a no conditionals; the browser shows the content that the document contains
CSS idiom @media, @supports and @container apply rules only when a condition is true

Every general-purpose language has an if statement or an if expression, so the differences are in the condition and the form. The languages differ in which values a condition accepts, in whether if gives a value, and in the forms that test and bind at the same time.

The example files show these differences. Python tests an empty list for truth, chains comparisons, binds a value with := in a condition, replaces a chain of elif with a dictionary and uses match with a guard. JavaScript shows which values are truthy, that else if is an if in an else, a chained conditional operator, an object lookup instead of conditions and ??=. Java binds a variable with an instanceof pattern, shows that ?: converts its operands to one type and can unbox a null, and shows a dangling else. C# tests ranges with relational patterns and uses a when guard. Go uses an if with a short statement, the err != nil check and a switch with no expression. Rust uses if as an expression, if let, let else and a let chain. C shows that any non-zero value is true, an assignment in a condition and #if. C++ uses if constexpr, an if with an initializer and likely.

PythonGitHub
# A condition can be any value: empty collections, 0 and None are false.
for items in ([], [1, 2]):
    if items:
        print("has", len(items), "items")
    else:
        print("empty")

# Comparisons chain, so 0 <= x < 10 tests both bounds.
x = 7
print(0 <= x < 10, 0 <= 12 < 10)

# The walrus operator binds a name inside the condition.
data = {"port": "8080"}
if (port := data.get("port")) is not None:
    print("port", int(port))

# A dictionary can replace a long chain of elif for fixed cases.
codes = {200: "OK", 404: "Not Found", 500: "Server Error"}
for code in (200, 404, 418):
    print(code, codes.get(code, "Unknown"))

# match with a guard chooses a case by shape and condition.
for point in [(0, 0), (3, 0), (2, 2), (1, 5)]:
    match point:
        case (0, 0):
            print(point, "origin")
        case (x, 0):
            print(point, "on the x axis")
        case (x, y) if x == y:
            print(point, "on the diagonal")
        case _:
            print(point, "elsewhere")
Output
empty
has 2 items
True False
port 8080
200 OK
404 Not Found
418 Unknown
(0, 0) origin
(3, 0) on the x axis
(2, 2) on the diagonal
(1, 5) elsewhere
  • Verdict: native. An empty list is false in a condition and a list with items is true. 0 <= x < 10 tests both bounds. := binds the value that the condition tests. A dictionary with get replaces a chain of elif for fixed codes. match with the guard if x == y finds the point on the diagonal.
#include <map>
#include <print>
#include <string>
#include <type_traits>

// if constexpr picks a branch at compile time; the other branch is discarded.
template <typename T>
std::string describe(T value) {
    if constexpr (std::is_integral_v<T>) {
        return "integer " + std::to_string(value * 2);
    } else if constexpr (std::is_floating_point_v<T>) {
        return "floating " + std::to_string(value / 2);
    } else {
        return "text " + std::string(value);
    }
}

int main() {
    std::println("{} | {} | {}", describe(21), describe(3.0), describe("hi"));

    // if with an initializer keeps the iterator inside the statement.
    std::map<std::string, int> stock{{"apple", 3}};
    for (const char* item : {"apple", "pear"}) {
        if (auto it = stock.find(item); it != stock.end()) {
            std::println("{} {}", item, it->second);
        } else {
            std::println("{} none", item);
        }
    }

    // [[likely]] and [[unlikely]] give the compiler a hint about the branch.
    int errors = 0;
    if (errors == 0) [[likely]] {
        std::println("no errors");
    } else [[unlikely]] {
        std::println("{} errors", errors);
    }
}
Output
integer 42 | floating 1.500000 | text hi
apple 3
pear none
no errors
  • Verdict: native. if constexpr keeps only the branch for the type of the argument, so describe("hi") compiles although the integer branch would not work for text. An if with an initializer keeps the iterator inside the statement. likely and unlikely are hints to the compiler.
JavaGitHub
public class Main {
    static String describe(Object o) {
        // instanceof with a pattern tests the type and binds a variable.
        if (o instanceof String s && !s.isEmpty()) {
            return "string of " + s.length();
        } else if (o instanceof Integer i) {
            return i > 0 ? "positive int" : "other int";
        }
        return "something else";
    }

    public static void main(String[] args) {
        System.out.println(describe("abc") + ", " + describe(5) + ", " + describe(""));

        // The two operands of ?: are converted to one type, so 1 prints as 1.0.
        boolean flag = true;
        System.out.println(flag ? 1 : 2.0);

        // With Integer and int operands, ?: unboxes, so a null Integer throws.
        Integer missing = null;
        try {
            int v = flag ? missing : 0;
            System.out.println(v);
        } catch (NullPointerException e) {
            System.out.println("NullPointerException from unboxing");
        }

        // The else belongs to the inner if, whatever the indentation says,
        // so r stays "none" when a is negative.
        int a = -5, b = 1;
        String r = "none";
        if (a > 0)
            if (b > 0)
                r = "both positive";
        else
            r = "a not positive";
        System.out.println(r);
    }
}
Output
string of 3, positive int, something else
1.0
NullPointerException from unboxing
none
  • Verdict: native. instanceof with a pattern tests the type and binds s or i, and && adds a second condition. flag ? 1 : 2.0 prints 1.0, because both operands become double. With a null Integer and an int operand, ?: unboxes and throws. The else belongs to the inner if, so r stays "none", although the indentation suggests otherwise.
#include <stdio.h>

#define VERBOSE 1

static int next_value(int *i) {
    static const int values[] = {4, 2, 0};
    return values[(*i)++];
}

int main(void) {
    /* A condition is true when it is not zero. */
    int count = 3;
    if (count) {
        printf("count is non-zero\n");
    }

    /* An else belongs to the nearest if that has no else. */
    int a = 5, b = -1;
    const char *r = "none";
    if (a > 0) {
        if (b > 0) {
            r = "both positive";
        } else {
            r = "a positive, b not";
        }
    }
    printf("%s\n", r);

    /* Assignment in a condition: the extra parentheses say it is on purpose. */
    int i = 0, v;
    while ((v = next_value(&i))) {
        printf("got %d\n", v);
    }

    /* The conditional operator gives a value. */
    int x = 3, y = 9;
    printf("max %d\n", x > y ? x : y);

    /* #if chooses code at compile time, before the program runs. */
#if VERBOSE
    printf("verbose build\n");
#else
    printf("quiet build\n");
#endif
    return 0;
}
Output
count is non-zero
a positive, b not
got 4
got 2
max 9
verbose build
  • Verdict: native. Any non-zero value is true in a condition. Braces make the inner if own the else. The extra parentheses around v = next_value(&i) mark an assignment in a condition, and the loop stops when the value is 0. x > y ? x : y chooses a value, and #if chooses code at compile time.
// Relational and logical patterns test ranges in one condition.
static string Range(int x)
{
    if (x is > 0 and < 10)
        return "one digit";
    else if (x is >= 10 and < 100)
        return "two digits";
    else
        return "other";
}
Console.WriteLine($"{Range(7)} {Range(42)} {Range(-3)}");

// A switch expression with a when guard.
static string Classify((int X, int Y) p) => p switch
{
    (0, 0) => "origin",
    (_, 0) => "on the x axis",
    var (x, y) when x == y => "on the diagonal",
    _ => "elsewhere",
};
Console.WriteLine($"{Classify((0, 0))} {Classify((3, 0))} {Classify((2, 2))}");

// ?. and ?? choose a value when something is null.
string? name = null;
Console.WriteLine(name?.ToUpper() ?? "anonymous");

// The condition must be a bool, so an int does not work as a condition.
int count = 3;
Console.WriteLine(count != 0 ? "non-zero" : "zero");
Output
one digit two digits other
origin on the x axis on the diagonal
anonymous
non-zero
  • Verdict: native. x is > 0 and < 10 tests a range with relational patterns. A switch expression uses a when guard for the diagonal. ?. and ?? choose "anonymous" when the name is null. A condition must be a bool, so the program writes count != 0.
JavaScriptGitHub
// A condition is truthy or falsy: "0" and [] are truthy, 0 and "" are falsy.
for (const v of [0, "0", "", [], null]) {
  if (v) {
    console.log(JSON.stringify(v), "truthy");
  } else {
    console.log(JSON.stringify(v), "falsy");
  }
}

// else if is an if statement inside the else branch.
function size(n) {
  if (n < 10) return "small";
  else if (n < 100) return "medium";
  else return "large";
}
console.log(size(5), size(50), size(500));

// The conditional operator gives a value, and it can be chained.
const t = 30;
console.log(t < 10 ? "cold" : t < 25 ? "mild" : "hot");

// An object lookup replaces a chain of conditions for fixed keys.
const handlers = { add: (a, b) => a + b, mul: (a, b) => a * b };
for (const op of ["add", "mul", "pow"]) {
  const f = handlers[op];
  console.log(op, f ? f(3, 4) : "unknown");
}

// ??= assigns only when the value is null or undefined.
const opts = { retries: 0 };
opts.retries ??= 3;
opts.timeout ??= 1000;
console.log(opts.retries, opts.timeout);
Output
0 falsy
"0" truthy
"" falsy
[] truthy
null falsy
small medium large
hot
add 7
mul 12
pow unknown
0 1000
  • Verdict: native. 0, "" and null are falsy, and "0" and [] are truthy. else if is an if statement in the else branch. A chained conditional operator chooses "hot". An object lookup replaces a chain of tests, and ??= assigns the default only to the missing timeout, not to the 0 of retries.
package main

import (
	"fmt"
	"strconv"
)

func main() {
	// An if can start with a short statement, whose variables live in the if.
	ages := map[string]int{"ann": 31}
	for _, name := range []string{"ann", "bob"} {
		if age, ok := ages[name]; ok {
			fmt.Println(name, age)
		} else {
			fmt.Println(name, "unknown")
		}
	}

	// The error check is the most common if in Go.
	for _, s := range []string{"12", "x"} {
		n, err := strconv.Atoi(s)
		if err != nil {
			fmt.Println("error:", err)
			continue
		}
		fmt.Println("number", n)
	}

	// A switch with no expression is a chain of if and else if.
	for _, t := range []int{5, 18, 30} {
		switch {
		case t < 10:
			fmt.Println(t, "cold")
		case t < 25:
			fmt.Println(t, "mild")
		default:
			fmt.Println(t, "hot")
		}
	}

	// Go has no conditional operator, so a value choice uses if.
	x, y := 3, 9
	larger := x
	if y > x {
		larger = y
	}
	fmt.Println("larger", larger)
}
Output
ann 31
bob unknown
number 12
error: strconv.Atoi: parsing "x": invalid syntax
5 cold
18 mild
30 hot
larger 9
  • Verdict: native. An if can start with a short statement, so age, ok := ages[name] lives only in the if and its else. The err != nil test handles the failed conversion. A switch with no expression is a chain of conditions. Go has no conditional operator, so a choice of value uses an if statement.
RustGitHub
fn parse_port(s: &str) -> Option<u16> {
    // let else leaves the function when the pattern does not match.
    let Ok(port) = s.parse::<u16>() else {
        return None;
    };
    if port == 0 { None } else { Some(port) }
}

fn main() {
    // if is an expression, so both branches must have the same type.
    let n = 7;
    let parity = if n % 2 == 0 { "even" } else { "odd" };
    println!("{n} is {parity}");

    // if let runs a block when a pattern matches.
    let config: Option<&str> = Some("8080");
    if let Some(text) = config {
        println!("config {text}");
    }

    // A let chain joins patterns and conditions with &&.
    for s in ["8080", "0", "abc"] {
        if let Some(p) = parse_port(s)
            && p >= 1024
        {
            println!("{s}: user port {p}");
        } else {
            println!("{s}: rejected");
        }
    }

    // The condition must be a bool; an integer does not work.
    let count = 3;
    println!("{}", if count != 0 { "non-zero" } else { "zero" });
}
Output
7 is odd
config 8080
8080: user port 8080
0: rejected
abc: rejected
non-zero
  • Verdict: native. if is an expression, so it gives parity its value. if let runs a block when Some matches. let else returns None from parse_port when the parse fails. A let chain joins the pattern and the test p >= 1024, so "0" and "abc" are rejected.
  • Guard clauses. A function that tests for bad cases first and returns early keeps its main path flat. Rust let else and Swift guard make this a form of the language.
  • Lookup tables. A map from keys to values or functions replaces a long chain of tests for fixed cases.
  • Pattern matching. match and switch with patterns test the shape of a value and bind its parts. See pattern matching.
  • Short-circuit operators. a && b() runs b only when a is true, so it is a small conditional. See short-circuit evaluation.
  • Branch-free code. cond * a + (1 - cond) * b and the conditional move instruction of a processor choose a value with no jump.

Pitfalls

  • Assignment in a condition. In C, if (x = 0) assigns and tests the result, which is always false. Compilers warn, and extra parentheses mark an assignment that is on purpose.
  • Truthiness. In Python, if value: is false for 0 and "" as well as for None. Test if value is None: when only None means missing.
  • Dangling else. Indentation does not decide where an else belongs in C, C++, Java and JavaScript. Use braces.
  • Mixed types in ?:. In Java, flag ? 1 : 2.0 gives 1.0, and an Integer operand that is null throws NullPointerException when the other operand is an int.
  • Long chains. A chain of ten else if tests is hard to check for missing cases. A match with an exhaustiveness check, or a table, is safer.

Cost

A conditional compiles to a comparison and a conditional jump. The processor predicts the direction of the jump, and a wrong prediction costs some cycles, so a branch whose direction is random is slower than one that is regular. For a simple choice of value, compilers often emit a conditional move with no jump.

History

The earliest conditional statement in Fortran, Wikipedia says, "was the arithmetic if statement which jumped to one of three labels depending on whether a value (of type integer, real, or double precision) is <0, 0, or >0"1. "The concept of conditional expression was first developed by John McCarthy during his research into symbolic processing and LISP in the late 1950s"1. McCarthy also suggested conditional expressions for ALGOL, and "ALGOL 60 and some other members of the ALGOL family allow if–then–else as an expression"1. In early dialects of BASIC, an if could contain only a goto, and the structured if, then, else of the ALGOL family became "one of the key elements of structured programming"1. C added the operator ? : and the rule for the dangling else, and most later languages copied both.

References

  1. Conditional (computer programming), Wikipedia, Introduction; History and development; Arithmetic if; Conditional expression
  2. Compound statements, The Python Language Reference, 8.1 The if statement
  3. The Java Language Specification, Java SE 25 Edition, Chapter 14, 14.9 The if Statement
  4. The Go Programming Language Specification, If statements
  5. if expressions, The Rust Reference, Introduction
  6. if...else, MDN Web Docs, Introduction
  7. Selection statements, C# language reference, The if statement; Case guards
  8. if statement, C++ reference, cppreference.com, Explanation; Constexpr if
  9. Conditional (ternary) operator, MDN Web Docs, Introduction
  10. The Java Language Specification, Java SE 25 Edition, Chapter 15, 15.25 Conditional Operator
  11. Expressions, The Python Language Reference, 6.13 Conditional expressions

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH0 no proof
  • add a proof in proofs/ (06.5)
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW4 complete
  • a review of the text: no review record reviews/F62G2R/text.yaml