The if statement in C++ programming language is used to execute a block of code only if a condition is true. It is used to check the truthness of the expression (In C++, all non-zero values are considered as true and zero is considered as false).
Syntax of If Statement
if(boolean_expression) {
// code to be execute if the boolean_expression is true
}
// code to be execute if the boolean_expression is true
}

- Condition written inside If statement parenthesis must be a boolean expression.
- The if statement first evaluates the boolean expression inside parenthesis.
- If the boolean_expression evaluated to true, then the block of code inside the if statement is executed.
- If boolean_expression evaluated to false, then the block of code inside the if statement is ignored and the next statement after if block is executed.
C++ If statement Example Program
#include <iostream> using namespace std; int main(){ int score; cout << "Enter your score : "; cin >> score; /* Using if statement to check whether a student failed in examination or not*/ if(score < 30){ // if condition is true then print the following cout << "You Failed :(\n"; } // This line always gets printed cout << "Your score : " << score; return 0; }
Output
Enter your score : 45 Your score : 45
Enter your score : 25 You Failed :( Your score : 25
Points to Remember about If Statement
- If statement allows the program to select an action based upon the user's input or the result of an expression. It gives us flexibility to change the logic of a program in different situations.
- The conditional_expression must be a boolean expression. It must evaluate to true or false value(In C++, all non-zero values are considered as true and zero is considered as false).
- We may use more than one condition inside if statement
For Example:
if(condition_one && condition_two) {
/* if code block */
} - Opening and Closing Braces are optional, If the block of code of if statement contains only one statement
For Example:
if(condition_expression)
statement1;
statement2;
In above example only statement1 will gets executed if condition_expression is true. To execute more than one statements after if statement evaluates to true, we have to use braces like the body of a function.