The if statement in C++ Programming



In its simplest form, the if statement evaluates a condition and executes the statements following it only if the condition is found to be true. An if statement starts with the word if, which is then followed by the condition in brackets:

if (<condition>)

The statements affected by the if statement are below, enclosed in the customary braces:

if (<condition>) {
// statements executed only if condition is true
}


If there is only a single statement inside the braces they can be omitted, but it is always good practice to include them to make sure that things are clear. The statements inside the braces should also always be indented to clearly show that the conditional statement controls them.

For example, if a program were required to divide two numbers it is important to check that the divisor is not equal to 0, since dividing by 0 gives an error. This can be achieved simply enough with an if statement:

float top, bottom;

cout << "Enter the first number: ";
cin >> top;
cout << "Enter the second number: ";
cin >> bottom;

if (bottom != 0) {
cout << top << " divided by " << bottom
<< " is " << top / bottom << endl;
}


This makes sure that the calculation takes place only if it is safe to do so. The statement inside the braces is executed only if the condition:

bottom != 0

is true, so it is executed only if the divisor does not equal 0.

Of course, if the divisor was 0 it would be useful to print a message to the user telling them why no output has been produced; as matters stand the user would just be left with no response at all from the program, a very bad example of
human–computer interaction. This can be done using the optional else part of an if statement.