0
0
CppHow-ToBeginner · 3 min read

How to Use If Else in C++: Simple Guide with Examples

In C++, use the if statement to run code only when a condition is true, and else to run code when it is false. The syntax is if (condition) { /* code */ } else { /* code */ }. This lets your program choose between two paths based on conditions.
📐

Syntax

The if else statement in C++ lets you run different code blocks based on a condition.

  • if (condition): Checks if the condition is true.
  • { }: Curly braces hold the code to run if the condition is true.
  • else: Runs code if the if condition is false.
  • { }: Curly braces hold the code to run if the condition is false.
cpp
if (condition) {
    // code runs if condition is true
} else {
    // code runs if condition is false
}
💻

Example

This example checks if a number is positive or not and prints a message accordingly.

cpp
#include <iostream>

int main() {
    int number = 5;
    if (number > 0) {
        std::cout << "The number is positive." << std::endl;
    } else {
        std::cout << "The number is zero or negative." << std::endl;
    }
    return 0;
}
Output
The number is positive.
⚠️

Common Pitfalls

Common mistakes when using if else in C++ include:

  • Forgetting curly braces { } when you have multiple lines inside if or else. This causes only the first line to be controlled by the condition.
  • Using = (assignment) instead of == (comparison) in the condition.
  • Missing semicolons ; after statements.
cpp
/* Wrong: Missing braces causes only first line to be conditional */
if (number > 0)
    std::cout << "Positive" << std::endl;
    std::cout << "Checked number." << std::endl; // runs always

/* Right: Use braces to group both lines */
if (number > 0) {
    std::cout << "Positive" << std::endl;
    std::cout << "Checked number." << std::endl;
}
📊

Quick Reference

Tips for using if else in C++:

  • Always use braces { } even for single statements to avoid mistakes.
  • Use == to compare values, not =.
  • You can chain multiple conditions with else if for more choices.
  • Indent your code inside if and else blocks for readability.

Key Takeaways

Use if to run code when a condition is true and else when it is false.
Always use curly braces { } to group code inside if and else blocks.
Use == to compare values, not = which assigns values.
Indent your code inside conditions to keep it clear and easy to read.
You can add more choices using else if between if and else.