The Simple if Statement
Learn how C++ uses the simple if conditional statement.
We'll cover the following...
In programming, we often come across points where we have to make a decision based on some certain input or output of a statement. In C++, to do this, we use some statements called conditional statements. We'll start with the most basic conditional statement, the if
statement.
if()
statement
The if statement takes one argument of type bool
or a function with return type bool
. Upon execution of the if
statement, the compiler moves to the if enclosed bracket if and only if the condition inside the if
statement is true
. Here, take a look at the flow diagram of the working conditional statement.
The syntax to write an if statement is:
if (<condition>){//if-enclosed code}
The if
statement as you can see is followed by a bracket ()
containing the condition, and doesn't end with a semicolon. After that the code that is to be executed if the condition within the brackets is true
is added. This if
code block is enclosed between opening and closing curly braces. Note that if there is only one line of code in the if
code block, we can do away with the curly braces. However, best practice in writing such code is to always add code, be it one line or multiple lines, within the curly braces.
Let's have a look at an example that uses a simple if statement.
#include <iostream>using namespace std;int main() {int age = 25;if (age >= 18) {cout << "You are an adult." << endl;}return 0;}
This code demonstrates a basic if
statement. On line 7, the program checks if the age
variable is greater than or equal to 18
. If the condition is ...