Ready to practice?
Sign up to access interactive coding exercises and track your progress.
Conditional Execution with If Statements
Execute different code paths based on conditions using if, else if, and else.
A conditional statement allows you to execute code only when certain conditions are true. C++ provides two primary types of conditionals: if statements and switch statements.
If statement syntax
The if statement is the most fundamental conditional in C++:
if (condition)
statement_when_true;
You can also include an optional else clause:
if (condition)
statement_when_true;
else
statement_when_false;
When the condition evaluates to true, the true statement executes. When it evaluates to false and an else clause exists, the false statement executes.
Here's a practical example:
#include <iostream>
int main()
{
std::cout << "Enter your age: ";
int age{};
std::cin >> age;
if (age >= 18)
std::cout << "You are an adult\n";
else
std::cout << "You are a minor\n";
return 0;
}
Sample runs:
Enter your age: 25
You are an adult
Enter your age: 14
You are a minor
Executing multiple statements with blocks
A common mistake beginners make is assuming multiple statements will execute conditionally:
#include <iostream>
namespace config
{
constexpr int passwordLength { 8 };
}
int main()
{
std::cout << "Enter password length: ";
int length{};
std::cin >> length;
if (length >= config::passwordLength)
std::cout << "Password is long enough\n";
else
std::cout << "Password is too short\n";
std::cout << "Please use at least 8 characters\n"; // problem line
return 0;
}
This produces unexpected output:
Enter password length: 12
Password is long enough
Please use at least 8 characters
The issue is that if and else can only be followed by a single statement. The indentation is misleading - the program behaves as if written like this:
#include <iostream>
namespace config
{
constexpr int passwordLength { 8 };
}
int main()
{
std::cout << "Enter password length: ";
int length{};
std::cin >> length;
if (length >= config::passwordLength)
std::cout << "Password is long enough\n";
else
std::cout << "Password is too short\n";
std::cout << "Please use at least 8 characters\n"; // always executes
return 0;
}
To execute multiple statements conditionally, use a compound statement (block):
#include <iostream>
namespace config
{
constexpr int passwordLength { 8 };
}
int main()
{
std::cout << "Enter password length: ";
int length{};
std::cin >> length;
if (length >= config::passwordLength)
std::cout << "Password is long enough\n";
else
{
std::cout << "Password is too short\n";
std::cout << "Please use at least 8 characters\n";
}
return 0;
}
Now the output is correct:
Enter password length: 12
Password is long enough
Enter password length: 5
Password is too short
Please use at least 8 characters
Implicit blocks
The compiler automatically creates an implicit block around single statements:
if (condition)
statement;
is equivalent to:
if (condition)
{
statement;
}
This usually doesn't matter, but causes problems when you try to define variables:
#include <iostream>
int main()
{
if (true)
int temperature{ 72 };
else
int temperature{ 68 };
std::cout << temperature << '\n';
return 0;
}
This won't compile. The compiler sees it as:
#include <iostream>
int main()
{
if (true)
{
int temperature{ 72 };
} // temperature destroyed
else
{
int temperature{ 68 };
} // temperature destroyed
std::cout << temperature << '\n'; // temperature doesn't exist here
return 0;
}
Variables defined inside implicit blocks are destroyed when the block ends, before you can use them.
Should you use blocks for single statements?
There's debate about whether single statements should be wrapped in blocks.
Arguments for always using blocks:
- Prevents accidentally adding code that looks conditional but isn't:
if (temperature >= 90)
turnOnAC();
turnOnFan(); // always executes - bug!
- Makes debugging easier. If you comment out the statement, the next line won't suddenly become conditional:
if (temperature >= 90)
// turnOnAC();
closeDoor(); // now conditional - unexpected!
- Consistency with constexpr if, which requires blocks.
The argument against blocks is that they spread code vertically, making it harder to see your entire function at once.
Consider putting single statements in blocks, especially while learning. Experienced developers sometimes skip blocks for conciseness, but it's safer to use them.
A middle-ground alternative is single-line if statements:
This avoids the problems mentioned above while staying compact. However, it makes debugging slightly harder since you can't set breakpoints on just the statement.
If-else chains vs independent if statements
Use if-else chains when you want only the first true condition to execute:
#include <iostream>
void testElse(int a, int b, int c)
{
if (a > 0) // always evaluated
std::cout << "positive ";
else if (b > 0) // only evaluated if a <= 0
std::cout << "middle ";
else if (c > 0) // only evaluated if a <= 0 and b <= 0
std::cout << "last ";
std::cout << '\n';
}
void testIndependent(int a, int b, int c)
{
if (a > 0) // always evaluated
std::cout << "positive ";
if (b > 0) // always evaluated
std::cout << "middle ";
if (c > 0) // always evaluated
std::cout << "last ";
std::cout << '\n';
}
int main()
{
testElse(5, 10, 15);
testIndependent(5, 10, 15);
return 0;
}
Output:
positive
positive middle last
In testElse(), only the first true condition executes. In testIndependent(), all true conditions execute.
When every branch returns a value, you can often omit else:
char getFirstMatch(int a, int b, int c)
{
if (a > 0)
return 'A'; // returns immediately
if (b > 0) // only evaluated if a <= 0
return 'B'; // returns immediately
if (c > 0) // only evaluated if a <= 0 and b <= 0
return 'C'; // returns immediately
return 'X';
}
This behaves identically to an if-else chain because return exits the function immediately, preventing subsequent conditions from being evaluated.
When all branches return, you can use independent if statements instead of if-else chains without changing behavior.
Summary
Conditional statements: Allow executing code only when certain conditions are true. C++ provides if statements and switch statements.
If statement syntax: if (condition) statement; optionally followed by else statement;. The condition evaluates to true or false, determining which branch executes.
Blocks for multiple statements: If and else can only be followed by a single statement. Use compound statements (blocks) with curly braces to execute multiple statements conditionally.
Implicit blocks: The compiler creates implicit blocks around single statements, which matters when defining variables inside the conditional—they're destroyed when the block ends.
Block recommendation: Consider always using blocks even for single statements to prevent bugs when adding code later, though single-line if statements (if (x) doSomething();) are a compact alternative.
If-else chains: Use when you want only the first true condition to execute. Once a condition is true, subsequent conditions in the chain aren't evaluated.
Independent if statements: All conditions are evaluated regardless of results. Use when you need to check multiple unrelated conditions.
Early returns: When all branches return values, you can use independent if statements instead of if-else chains because return immediately exits the function.
If statements are the fundamental building block for decision-making in C++. Understanding when to use if-else chains versus independent if statements is crucial for writing correct, efficient conditional logic.
Conditional Execution with If Statements - Quiz
Test your understanding of the lesson.
Practice Exercises
Ticket Pricing System
Implement a ticket pricing system with different rates based on age categories.
Lesson Discussion
Share your thoughts and questions
No comments yet. Be the first to share your thoughts!