Using The C++ If Statement


In C++ the if statement is particularly useful for running code only if a certain condition is met. It differs from loops in that the code is only executed once per the condition being met. Learning how to use the if statement is another great step to being a competent C++ programmer. 

How Does The C++ If Statement Work?


C++ switch statement flowchart example

As seen in the flowchart to the right, the if statement in C++ works by running code based on if a conditional statement returns true. If it does then the statement in the if body will execute and if it doesn’t it will end or jump to the next line in the program. The basic syntax for an if statement is shown below.

if(condition)
{
statement
}

As seen, using the if statement can be very simple. All you have to do is declare a variable and within your if statement check to see if a certain condition is true. If that condition is true then the statement within the if statement body will be executed. Once the if statement is executed the code will exit the if conditional and will jump to the next bit of code in your program. If the statement returns false then the program will simply jump to the next part of the program and will ignore the statements within the body of if. 

C++ Examples of If Statements


Now that we have a basic feel of how the C++ if statement works lets look at a couple of examples. In the first example we have a simple if statement that checks to see if the value of x is greater than 10. If it is then the statement within the if body will be executed. Since x is greater than 10 in this case since we set x = 11 the statement inside of the if body will run.

//C++ if statement example 1
#include <iostream>
int x = 11;
int main()
{
if(x > 10)
{
std::cout << "x is greater than 10" << endl;
}
return 0;
}

Output:

x is greater than 10

Now lets look at another example on how to use the C++ if statement. In this example we will make a simple guessing game. In this game the programmer can set a variable, x, to be any number they like. They will then ask the player to select a number. If the number they picked is the same as the number the programmer has set, the console will output that they have guessed correctly. In this case the programmer has set the integer value of x to be 4 and the player has guessed correctly as displayed in the output.

//Example 2
#include <iostream>
int x = 4, y;
int main()
{
std::cout << "Guess a number between 1 and 10:n";
std::cin >> y;
    if(x == y)
    {
    std::cout << "You have guessed correctly!" << std::endl;
    }
return 0;
}

Output:

Guess a number between 1 and 10: 
4 
You have guessed correctly!