Decision making: if and switch
Decision making in C using if, if–else, nested/else-if ladder, and switch with case/default/break, including syntax, rules, flow ideas, worked programs, and exam-focused guidance.
Drafted with Aria, reviewed by the AiCanCode.org team · Updated . How we write and check our notes. Spotted an error? Use Give Feedback at the bottom of the page.
Why it matters
Decision making tells a program which path to follow based on conditions. Engineers use it to enforce safety limits, select modes (manual/auto), log alarms, and choose formulas or data processing steps based on sensor values or user choices. Without decision making, programs would do the same thing every time and could not react to inputs.
Key ideas
- Condition: An expression evaluated to decide a path. In C, any scalar expression can be a condition. It is considered false if its value is 0, and true if its value is any non-zero value. Assumption: evaluation follows C operator precedence and conversions.
- Boolean expression: An expression that uses relational or logical operators to yield true/non-zero or false/0 (e.g.,
a > b && b != 0). C does not have a built-in Boolean keyword in pre-C99, butintis used conventionally;_Bool/stdbool.hexist but are outside this topic’s focus. - Relational operators:
>,<,>=,<=,==,!=. They compare two values and produce 0 (false) or 1 (true) of typeintin C. - Logical operators:
&&(logical AND),||(logical OR),!(logical NOT). Result is 0 or 1. They use short-circuit evaluation: evaluation stops as soon as the result is determined (e.g., inA && B, ifAis false (0),Bis not evaluated; inA || B, ifAis true (non-zero),Bis not evaluated). - Selection statements: The two structured selection constructs in C are if and switch.
- Block (compound statement): A sequence of statements enclosed in
{and}. It acts as a single statement and introduces a new scope for local declarations. - if statement: Tests a condition and optionally executes statements when the condition is true.
- Forms:
- Simple if: executes when condition is true.
- if–else: chooses between two alternatives.
- else–if ladder: multiple mutually exclusive tests checked in order.
- Nested if: an if statement inside another if or else block.
- Forms:
- Dangling else rule: In C, each
elseis associated with the nearest preceding unmatchedif. To avoid confusion, use braces{}to make the intended association explicit. - switch statement: Multi-way selection that compares one controlling expression with case labels (constant integral expressions) and transfers control to the matching case.
- case label: Introduces a labeled position in a switch; must be a constant expression of an integer type and unique within that switch.
- default label: Optional label executed when no case matches.
- break: Exits the nearest enclosing switch (or loop). Without
break, execution falls through into the next case. - Fall-through: When a case matches and there is no
break, execution continues into subsequent case(s) until abreakor the end of the switch. Use intentionally and document it.
- Types allowed in switch: The controlling expression must be of an integer type after the usual integer promotions. Characters (
char), integers (int), enumerations (enum), andlong/short(after promotion) are allowed. Floating types (float,double) and strings are not allowed. - Constant expression for case: Each
casevalue must be a compile-time constant and not duplicate any other case in the same switch. Note: In C (unlike C++), aconst intvariable is not a constant expression and cannot be used in acaselabel. - Operator precedence reminder (from Operators and expressions topic):
!has higher precedence than relational operators (<,<=,>,>=), which have higher precedence than equality operators (==,!=), which have higher precedence than&&, which has higher precedence than||. Use parentheses when in doubt. - Assignment vs equality:
=assigns;==compares. Using=instead of==in conditions is a common bug. - Implicit conversions in conditions: When a non-integer is used in a condition, it is converted to an integer (0 or non-zero). For floating comparisons, avoid exact
==due to rounding; prefer tolerance comparisons for real-world values (topic belongs with Operators and expressions, but relevant warning here). - When to use if vs switch:
- Use
if/else-ifwhen comparing ranges, complex conditions, or different variables/expressions. - Use
switchwhen checking one expression against many fixed constant values (menu choices, character commands, enum states).switchcan be clearer and sometimes faster.
- Use
Exam-typical diagrams (describe to draw):
- Flowchart for if–else: Start → Input → Decision diamond labeled with the condition (e.g.,
x > 0?) → two arrows: True to a process box “Do A”; False to a process box “Do B” → both join to End. - Flowchart for switch: Start → Input → Process box “Compute expression E” → Decision diamond or a multi-branch symbol with outgoing labeled arrows
case v1,case v2, …,defaultto separate process boxes “Action 1”, “Action 2”, … → each goes to a join → End. Label the need forbreakat the end of each Action box to prevent fall-through.
Formulas
For programming, remember the exact syntax patterns:
if (condition) statement;- condition: any expression; non-zero is true, 0 is false. statement: a single statement or a block
{ ... }.
- condition: any expression; non-zero is true, 0 is false. statement: a single statement or a block
if (condition) { statements }if (condition) { statements } else { statements }if (c1) { ... } else if (c2) { ... } else if (c3) { ... } else { ... }switch (expression) { case constant1: statements; break; case constant2: statements; break; default: statements; }case 'A':(character literal constant allowed)break;(exits the nearest switch)default:(optional, executed if no case matches)/* fall through */(comment to indicate intentional fall-through)
Key operator syntax reminders:
==,!=,<,<=,>,>=for comparisons&&,||,!for logical operations (short-circuit)- Use parentheses to group:
(a <= b && b <= c)
Worked examples
Example 1 — Grading with else–if ladder (ranges): Program: Reads marks (0–100) and prints grade using if–else-if. Demonstrates range checks and correct order.
#include <stdio.h>
int main(void) {
int marks;
if (scanf("%d", &marks) != 1) {
return 0; // no output if invalid input
}
if (marks < 0 || marks > 100) {
printf("Invalid marks\n");
} else if (marks >= 90) {
printf("Grade: O\n"); // Outstanding
} else if (marks >= 80) {
printf("Grade: A\n");
} else if (marks >= 70) {
printf("Grade: B\n");
} else if (marks >= 60) {
printf("Grade: C\n");
} else if (marks >= 50) {
printf("Grade: D\n");
} else {
printf("Grade: F\n");
}
return 0;
}
Sample input:
78
Exact output:
Grade: B
Why it works: The first true condition stops the ladder. Ordering from highest to lowest avoids overlapping ranges and unreachable branches.
Example 2 — Menu using switch with break and default: Program: Reads a choice (1–4) and two integers, then performs the selected operation. Shows case labels, break, and default.
#include <stdio.h>
int main(void) {
int choice, a, b;
if (scanf("%d", &choice) != 1) return 0;
if (scanf("%d %d", &a, &b) != 2) return 0;
switch (choice) {
case 1:
printf("Sum = %d\n", a + b);
break;
case 2:
printf("Difference = %d\n", a - b);
break;
case 3:
printf("Product = %d\n", a * b);
break;
case 4:
if (b == 0) {
printf("Division by zero error\n");
} else {
printf("Quotient = %d\n", a / b); // integer division
}
break;
default:
printf("Invalid choice\n");
break;
}
return 0;
}
Sample input:
3
5 2
Exact output:
Product = 10
Notes: default handles any choice other than 1–4. break prevents fall-through from one operation to another.
Example 3 — Character command with intentional fall-through: Program: Reads a letter command; both 'q' and 'Q' quit using fall-through, 'h'/'H' show help; other characters report unknown.
#include <stdio.h>
int main(void) {
int ch = getchar();
switch (ch) {
case 'q':
case 'Q':
printf("Quit selected\n");
break;
case 'h':
case 'H':
printf("Help selected\n");
break;
default:
printf("Unknown command\n");
break;
}
return 0;
}
Sample input:
Q
Exact output:
Quit selected
Model theory answer segment — Dangling else and how to avoid it:
- Statement: “In C, an
elseis associated with the nearest previous unmatchedif.” - Example without braces:
- Code:
if (a > 0) if (b > 0) x = 1; else x = 2; - Association: The
elsebinds toif (b > 0), not toif (a > 0).
- Code:
- Safer version with braces:
if (a > 0) { if (b > 0) { x = 1; } else { x = 2; } }
- Conclusion: Always use braces to make the intended structure explicit, especially in nested conditionals.
Common mistakes
- Forgetting braces when multiple statements should run under an
iforelse, leading to only the first statement being conditional. - Overlapping or wrongly ordered conditions in an else–if ladder (e.g., checking
>= 60before>= 80), making higher grades unreachable. - Missing
breakin aswitch, causing unintended fall-through and multiple outputs. - Using non-constant expressions in
caselabels (e.g.,case x+1:whenxis a variable), which is illegal. - Using
switchon floats or strings, which is not allowed; the controlling expression must be an integer type (after promotions) or an enum. - Forgetting to handle
default(especially in user interfaces) causing no action for unexpected inputs. - Writing complex conditions without parentheses, relying on precedence incorrectly (e.g.,
a && b || cwhen the intent was(a && (b || c))). - Comparing floating-point values using
==exactly; due to rounding, it may fail. Prefer a tolerance check in anif(belongs to Operators topic but causes errors here). - Not considering divide-by-zero in a branch that does division.
For your exam
- Short notes: “Dangling else rule,” “Fall-through in switch,” “When to prefer switch over if–else,” “Short-circuit evaluation with example.” Include precise rule statements and a small code snippet.
- Programs: “Menu-driven calculator using switch,” “Grade classification using else–if ladder,” “Character command handler with both uppercase and lowercase using fall-through,” “Find maximum of three numbers using nested if.” Include: correct input handling, correct ordering of conditions, exact outputs, and comments optional but clear.
- Diagrams: Flowchart for
if–elseandswitch. Draw the decision diamond and label True/False arrows; for switch, show separate branches for cases and default, and notebreak. - Reasoning questions: “Explain why
switchcannot usefloat.” Answer: Case labels are integral constant expressions; controlling expression must be integer type after promotion; floats cannot be used. “Explain short-circuit with side effects.” Show that inA && B, ifAis false,Bis not evaluated. - Style/best practice: “How to avoid dangling else and unintended fall-through?” Answer: Use braces; place
break; add comments/* fall through */when intentional; keep cases ordered and grouped.
A full-marks programming answer generally includes: correct syntax, correct logic for all input cases (including edge cases), appropriate use of break/default, clean and minimal I/O, and sample output matching exactly when asked.
Quick check
- What is the truth value of the condition in C when an expression evaluates to 0? What about any non-zero value?
- Can you write
switchon adoubleexpression? Why or why not? - In the code
switch(x){ case 1: printf("A"); case 2: printf("B"); break; }, what is the exact output whenxis 1?
Answers: 1) 0 is false; any non-zero value is true. 2) No; switch requires an integer type (after promotions) and case labels must be integral constant expressions. 3) It prints AB because of fall-through from case 1 to case 2 due to missing break after printing A.
Finished this topic? Mark it so your progress, study plan and readiness keep up.
Stuck on something here?