Conditional statement

Also known as: if statement

On this page 7

A conditional statement, most commonly written as an if statement, is a programming construct that executes a block of code only when a specified condition evaluates to true, and optionally executes an alternative block when it is false. Among programming fundamentals it is the basic mechanism of decision-making: together with sequence and loops, it forms one of the three control structures from which every algorithm can be built.

The condition is a Boolean expression, such as age >= 18 or user.isActive, that the program evaluates at run time. Depending on the result, control flow branches to one path or another, which is why conditional statements are also called branching statements.

How a conditional statement controls program flow

When execution reaches a conditional statement, the program evaluates the condition first, then jumps to the matching branch and skips the others. After the chosen branch finishes, execution continues with the first statement after the whole construct. At machine level, a compiler translates this into a comparison followed by a conditional jump instruction.

The construct has several standard forms. A plain if runs code or does nothing; if-else chooses between two paths; an else-if chain tests several conditions in order and runs only the first branch whose condition is true. Conditions are tested from top to bottom, so the order of branches matters whenever conditions overlap.

FormStructureTypical use
Ifif (condition) { ... }Optional action, such as logging a warning
If-elseif (condition) { ... } else { ... }Two mutually exclusive outcomes
Else-if chainif ... else if ... elseRanges or several ordered cases
Nested ifAn if inside another branchDecisions that depend on earlier decisions
Guard clauseif (invalid) return; at the startRejecting bad input early
Basic forms of the conditional statement

Conditions, truthiness and short-circuit evaluation

Conditions are built from comparison operators such as ==, !=, > and >=, combined with logical operators AND, OR and NOT. Most languages use short-circuit evaluation: in a && b, the right side is evaluated only if the left side is true, and in a || b only if the left side is false. This allows safe patterns such as user != null && user.isAdmin.

Languages differ in what they accept as a condition. Strictly typed languages such as Java and C# require a true Boolean value, while C, Python and JavaScript apply truthiness rules that treat values such as zero, empty strings or null as false. These rules are convenient but cause subtle bugs when a valid value like zero is mistaken for a missing one.

LanguageValues treated as falseNotable trap
CZero and null pointersif (x = 5) assigns instead of comparing
PythonFalse, None, 0, empty string and empty collectionsAn empty list fails the condition
JavaScriptfalse, 0, empty string, null, undefined, NaNLoose equality == converts types
Java and C#Only the Boolean value falseNon-Boolean conditions do not compile
Values treated as false in selected languages

Several constructs serve the same purpose as an if statement in more specialized form. Choosing among them is mainly a question of readability and the shape of the decision, although compilers can sometimes produce faster code for a switch over many integer cases by building a jump table.

ConstructWhat it doesBest suited for
If-else statementExecutes one of several blocksGeneral decisions with arbitrary conditions
Switch statementSelects a case by matching one valueMany discrete values of one variable
Ternary operatorReturns one of two values as an expressionShort assignments such as choosing a label
Pattern matchingMatches structure and type, binds variablesData with several shapes or variants
Lookup table or mapSelects a value or function by keyReplacing long chains of equality tests
Conditional constructs compared

An important distinction is between statements and expressions. A classic if statement performs actions but produces no value, whereas the ternary operator and, in languages such as Kotlin, Rust or Scala, the if construct itself are expressions that return a value. This allows assigning the result of a decision directly to a variable.

Writing clear and correct conditionals

Readable conditionals have shallow nesting and well-named conditions. Deeply nested branches, sometimes called the arrow anti-pattern, force readers to keep many states in mind. Guard clauses that handle invalid cases first and return early flatten the structure, and extracting a complex expression into a well-named variable or function such as isEligibleForDiscount documents its intent.

  • Cover every case: end an else-if chain with an else branch that handles or reports unexpected values.
  • Avoid comparing floating-point numbers for exact equality; compare against a small tolerance instead.
  • Prefer positive conditions: if (isValid) reads more easily than a double negation.
  • Use braces consistently, even for single statements, to prevent errors when lines are added later.

Common errors and their causes

Conditional statements are a frequent source of logic errors that compile without warnings. The table lists typical defects, their causes and the standard remedy.

SymptomLikely causeFix
Branch always runsAssignment used instead of comparisonUse the equality operator and enable compiler warnings
Wrong branch for boundary valuesOff-by-one in > versus >=Test the exact boundary values
Later branch never reachedBroader condition placed earlierOrder conditions from specific to general
Crash on missing dataNull checked after it is usedCheck for null first or use short-circuit order
Unexpected fallthroughMissing break in a switch caseAdd break or use a construct without fallthrough
Typical conditional defects

Thorough testing of conditionals aims at branch coverage, meaning every branch runs at least once in the test suite, and ideally at boundary values on each side of every comparison.

A plain-language summary

A conditional statement is how a program makes a choice. It works like a rule you follow every day. If it is raining, take an umbrella. Otherwise, leave it at home.

The computer checks a question that has a yes or no answer. If the answer is yes, it does one thing, and if it is no, it does another. Almost every useful program is full of these small decisions, from checking a password to choosing which page to show next.

An example from practice

An online shop calculates shipping costs with a chain of conditional statements. A guard clause first rejects orders with an empty cart. Then an else-if chain checks the order total: orders of 100 dollars or more ship free, orders from 50 dollars pay a reduced fee of 4.99 dollars, and all others pay 9.99 dollars.

During testing, a developer notices that an order of exactly 100 dollars is charged 4.99. The cause is the condition total > 100, which excludes the boundary value. Changing it to total >= 100 and adding tests for 49.99, 50, 99.99 and 100 dollars fixes the defect before release, and the final rule matches the published shipping policy exactly.