Skip to content

Beginner · Decisions, loops and functions · topic 5 of 42 · 25 min

Operators and decisions: if, else and switch

Explanation

Comparison operators (==, !=, <, >, <=, >=) give true or false, and logical operators (&&, ||, !) combine them. if / else if / else runs one branch; switch picks a case by a whole-number or character value. Never confuse = (assign) with == (compare).

Why decisions?

Real programs must choose: pass or fail, free delivery or not, child fare or adult fare. A condition is an expression that is either true or false. if runs a block of code only when its condition is true.

Comparison and logical operators

OperatorMeaningExample (true)
==equal tomarks == 100
!=not equal tograde != 'F'
< > <= >=less / greater (or equal)age >= 18
&&and: both must be trueage >= 18 && hasId
||or: at least one trueday == 'S' || holiday
!not: flips true and false!paid
cpp
#include <iostream>

int main() {
    int marks = 72;
    if (marks >= 90) {
        std::cout << "Grade A\n";
    } else if (marks >= 60) {
        std::cout << "Grade B\n";
    } else if (marks >= 33) {
        std::cout << "Grade C\n";
    } else {
        std::cout << "Fail\n";
    }
}
Checks run from top to bottom and only the first true branch runs. Prints Grade B.

Short-circuit evaluation

&& stops as soon as the left side is false, and || stops as soon as the left side is true. This is called short-circuiting, and it is useful for safety checks: in if (count != 0 && total / count > 50), the division only happens when count is not zero.

The ternary operator

cpp
int age = 70;
double fare = (age >= 60) ? 600.0 : 1000.0;   // senior fare
condition ? valueIfTrue : valueIfFalse is a compact if/else that gives a value.

switch for fixed choices

cpp
char choice = 'b';
switch (choice) {
    case 'a':
        std::cout << "Check balance\n";
        break;
    case 'b':
        std::cout << "Send money\n";
        break;
    default:
        std::cout << "Invalid option\n";
}
switch compares one integer or character value against fixed cases. Prints Send money.
Careful: Forgetting break in a switch makes the program "fall through" into the next case and run it too. GCC warns about this with -Wextra, and Clang with -Wimplicit-fallthrough. If you really want fall-through, mark it with [[fallthrough]]; so readers know it is on purpose.

switch works only with integral types (int, char, enum and similar), not with std::string or double. For text, use if / else if.

The = versus == trap

cpp
int seats = 0;
if (seats = 5) {          // BUG: assigns 5, which is "true"
    std::cout << "Always runs!\n";
}
if (seats == 5) { }       // correct comparison
GCC warns: "suggest parentheses around assignment used as truth value". Another reason to keep warnings on.
Think of it like this: An if/else if chain is like a ticket checker at a metro gate. He checks the first rule (has a pass?), then the next (has a token?), and lets you through at the FIRST rule that matches. He does not check the remaining rules once one has matched.

Common mistakes

  • A semicolon right after the condition: if (x > 5); { ... } runs the block always, because the ; is an empty statement.
  • Leaving out braces and adding a second line later: only the first line belongs to the if. Always use braces.
  • Writing 10 < x < 20 to test a range. It means (10 < x) < 20, which is always true. Write x > 10 && x < 20.
  • Comparing doubles with ==: 0.1 + 0.2 == 0.3 is false. Compare with a small tolerance instead.

Need help?

Stuck on a word or an idea? Search this course, or every course, and jump straight to the explanation or a worked question.

Try:

Watch the lesson

Operators and decisions: if, else and switch · 1/6

Decisions

Programs need to make choices. In this lesson you will use if, else and switch.

Prefer a video by a teacher? Find free videos on “c++ if else switch logical operators tutorial beginners” on YouTube ↗

In real life: Free delivery rule on a shopping app

Shopping apps like Flipkart and Amazon show "free delivery" when your cart crosses a limit, or when you are a member. One if statement with || decides it, and the ternary operator picks the delivery charge.

cpp
#include <iostream>

int main() {
    double cartTotal = 449.0;
    bool isMember = false;
    bool freeDelivery = cartTotal >= 499 || isMember;
    double charge = freeDelivery ? 0.0 : 40.0;
    std::cout << "Delivery charge: Rs " << charge << '\n';   // 40
}
Changes to 0 when the cart reaches 499 or the user is a member.

Practice (0/4 done)

Task 1 · Question

int x = 15; What prints? if (x > 10) std::cout << "big"; else std::cout << "small";

Task 2 · Question

What does this print? int d = 2; switch (d) { case 1: std::cout << "Mon "; case 2: std::cout << "Tue "; case 3: std::cout << "Wed "; default: std::cout << "?"; }

Task 3 · Question

Which condition correctly checks that age is between 18 and 60, inclusive?

Task 4 · Practice

Write an electricity bill program: read the units used. The first 100 units cost Rs 3 each, the next 100 (101–200) cost Rs 5 each, and anything above 200 costs Rs 8 each. Print the total.

Quick quiz

Question 1

1.What is the value of (5 > 3) && (2 > 4)?

Question 2

2.In if (n != 0 && 100 / n > 5), what happens when n is 0?

Question 3

3.Which type can NOT be used in a switch?

Question 4

4.int a = 7; int b = (a % 2 == 0) ? 1 : 0; What is b?

Question 5

5.Why does if (x = 0) never run its block?

Read more (free)

Open a question to see the answer and why. The first ones are this topic's own quiz, so try the quiz above before you peek.

What is the value of (5 > 3) && (2 > 4)?

Answer: false

The left side is true but the right side is false, and && needs both.

In if (n != 0 && 100 / n > 5), what happens when n is 0?

Answer: The right side is never evaluated, so it is safe

Short-circuit: && stops at the false left side.

Which type can NOT be used in a switch?

Answer: std::string

switch needs an integral or enum value. Use if / else if for strings.

int a = 7; int b = (a % 2 == 0) ? 1 : 0; What is b?

Answer: 0

7 % 2 is 1, so the condition is false and b gets 0.

Why does if (x = 0) never run its block?

Answer: Because it assigns 0 to x, and 0 counts as false

The assignment gives the value 0, which is false. You probably meant x == 0.

A switch case has code but no break. What happens?Related

Answer: Compile error: control cannot fall through

C# does not allow fall-through from a non-empty case (error CS0163).

From Decisions: if, else, switch and switch expressions

How many branches of if / else if / else can run?Related

Answer: At most one

Only the first true branch runs.

From Decisions: if, else and the ternary

How do you make one switch case match both 1 and 2?Related

Answer: case 1, 2:

List several values separated by commas in one case.

From Decisions with if and switch

Which types can a standard C switch use?Related

Answer: Integer types like int, char and enums

Case labels must be integer constants.

From Decisions: if, else and switch

Pass the quiz (60% or more) or mark this topic as done when you are ready.

Your progress is saved on this device only.

Next steps

  1. 3 more topics in “Decisions, loops and functions” before its exam: Loops: for, while, do-while and range-for, Functions: declare, define, call and return, Overloading, default arguments and recursion.
  2. Module 2 exam: Decisions, loops and functions · 12 questions · 20 min, without help. 4 topics of this module still to finish first.
  3. Then the next module, References, pointers, arrays and strings. 42 topics left in the course before the final exam.

← Previous: Reading input and formatting output