Beginner · Decisions, loops and functions · topic 5 of 42 · 25 min
Operators and decisions: if, else and switch
Explanation
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
| Operator | Meaning | Example (true) |
|---|---|---|
| == | equal to | marks == 100 |
| != | not equal to | grade != 'F' |
| < > <= >= | less / greater (or equal) | age >= 18 |
| && | and: both must be true | age >= 18 && hasId |
| || | or: at least one true | day == 'S' || holiday |
| ! | not: flips true and false | !paid |
#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";
}
}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
int age = 70;
double fare = (age >= 60) ? 600.0 : 1000.0; // senior fareswitch for fixed choices
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 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
int seats = 0;
if (seats = 5) { // BUG: assigns 5, which is "true"
std::cout << "Always runs!\n";
}
if (seats == 5) { } // correct comparisonCommon 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
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.
#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
}Practice (0/4 done)
int x = 15; What prints? if (x > 10) std::cout << "big"; else std::cout << "small";
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 << "?"; }
Which condition correctly checks that age is between 18 and 60, inclusive?
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
Read more (free)
Related help
Before this, learn
This topic builds on these. If something here feels new, open them first.
Related topics
- Loops: for, while, do-while and range-forDecisions, loops and functions · same module
- Functions: declare, define, call and returnDecisions, loops and functions · same module
- Overloading, default arguments and recursionDecisions, loops and functions · same module
- Decisions: if, else, switch and switch expressionsC# and .NET · Decisions, loops and methods
- Decisions: if, else and the ternaryJava Programming (Core to Spring Boot) · Control flow and methods
- Decisions with if and switchGo Programming (backend and cloud) · Control flow and functions
Questions people ask about this
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).
How many branches of if / else if / else can run?Related
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.
Which types can a standard C switch use?Related
Answer: Integer types like int, char and enums
Case labels must be integer constants.
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
- 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.
- Module 2 exam: Decisions, loops and functions · 12 questions · 20 min, without help. 4 topics of this module still to finish first.
- Then the next module, References, pointers, arrays and strings. 42 topics left in the course before the final exam.