The if Statement
In structured programming, flow control dictates execution paths beyond mere sequential steps. Conditional branching allows a program to execute specific blocks of code based on boolean evaluations.
The fundamental construct for branching is the if statement. It evaluates a condition; if the condition evaluates to non-zero (true), the subsequent statement executes. Zero evaluates to false, skipping execution.
if (status_code != 0)
handle_failure();To execute multiple statements conditionally, enclose them in a block:
if (request_is_valid) {
parse_data();
process_request();
}The else Clause and Multi-Branching
An else block provides an alternative path when the if condition evaluates to false.
if (memory_available)
allocate_resource();
else
trigger_gc();For multiple distinct conditions, else if chains sequential evaluations:
if (priority_level == HIGH)
execute_immediately();
else if (priority_level == MEDIUM)
queue_task();
else
defer_task();When nesting if statements, the "dangling else" rule applies: an else always binds to the closest unpaired if.
if (outer_flag)
if (inner_flag)
execute_both();
else
execute_outer_only(); // Binds to the inner ifRelational and Equality Operators
Conditions often rely on comparisons. C provides <, >, <=, >=, == (equality), and != (inequality).
A common pitfall is chaining relational operators mathematically, like x > y > z. C evaluates this left-to-right, resulting in a boolean comparison against z. To properly check multiple bounds, use logical ANDs: x > y && y > z. Another frequent mistake is using the assignment operator = instead of the equality operator == inside conditions.
The Ternary Conditional Operator
For simple two-way branches, the ternary operator offers concise syntax:
result = (threshold_exceeded) ? calculate_overflow() : compute_norm();If threshold_exceeded is true, calculate_overflow() executes and its result assigns to result. Otherwise, compute_norm() evaluates.
Logical Operators and Short-Circuit Evaluation
Complex conditions combine expressions using logical operators: && (AND), || (OR), and ! (NOT).
AND (&&) requires both operands true. OR (||) requires at least one true. NOT (!) inverts the boolean value.
Both && and || exhibit short-circuit behavior:
- For
&&, if the left operand is false, the right operand is never evaluated. - For
||, if the left operand is true, the right operand is skipped.
if (pointer != NULL && pointer->is_active)
// Safe access due to short-circuitingThe switch Statement
A switch statement evaluates an integral expression and jumps to a matching case label. If no match exists, execution falls to default if provided.
switch (error_category) {
case ERR_IO:
log_io_fault();
break;
case ERR_NETWORK:
retry_connection();
break;
default:
log_unknown();
break;
}Without a break statement, execution "falls through" from the matched case into subsequent ones. The case labels act merely as entry points, not autonomous blocks.