The most basic kind of conditional branch in C++ is the if statement. An if statement takes the form:
if (expression)
statement
or
if (expression)
statement
else
statement2
If the expression evalutes to true (non-zero), the statement executes. If the expression evaluates to false, the else statement is executed if it exists.
Here is a simple program that uses an if statement:
#include <iostream>
int main()
{
using namespace std;
cout << "Enter a number: ";
int nX;
cin >> nX;
if (nX > 10)
cout << nX << "is greater than 10" << endl;
else
cout << nX << "is not greater than 10" << endl;
return 0;
}
Note that the if statement only executes a single statement if the expression is true, and the else only executes a single statement if the expression is false. In order to execute multiple statements, we can use a block:
#include <iostream>
int main()
{
using namespace std;
cout << "Enter a number: ";
int nX;
cin >> nX;
if (nX > 10)
{
// both statements will be executed if nX > 10
cout << "You entered " << nX << endl;
cout << nX << "is greater than 10" << endl;
}
else
{
// both statements will be executed if nX <= 10
cout << "You entered " << nX << endl;
cout << nX << "is not greater than 10" << endl;
}
return 0;
}
It is possible to chain if-else statements together:
int main()
{
using namespace std;
cout << "Enter a number: ";
int nX;
cin >> nX;
if (nX > 10)
cout << nX << "is greater than 10" << endl;
else if (nX < 5)
cout << nX << "is less than 5" << endl;
// could add more else if statements here
else
cout << nX << "is between 5 and 10" << endl;
return 0;
}
It is also possible to nest if statements within other if statements:
#include <iostream>
int main()
{
using namespace std;
cout << "Enter a number: ";
int nX;
cin >> nX;
if (nX > 10)
// it is bad coding style to nest if statements this way
if (nX < 20)
cout << nX << "is between 10 and 20" << endl;
// who does this else belong to?
else
cout << nX << "is greater than 20" << endl;
return 0;
}
The above program introduces a source of potential ambiguity called a dangling else problem. Is the else statement in the above program matched up with the outer or inner if statement?
The answer is that an else statement is paired up with the last unmatched if statement in the same block. Thus, in the program above, the else is matched up with the inner if statement.
To avoid such ambiguities when nesting complex statements, it is generally a good idea to enclose the statement within a block. Here is the above program written without ambiguity:
#include <iostream>
int main()
{
using namespace std;
cout << "Enter a number: ";
int nX;
cin >> nX;
if (nX > 10)
{
if (nX < 20)
cout << nX << "is between 10 and 20" << endl;
else // attached to inner if statement
cout << nX << "is greater than 20" << endl;
}
return 0;
}
Now it is much clearer that the else statement belongs to the inner if statement.
Encasing the inner if statement in a block also allows us to explicitly attach an else to the outer if statement:
#include <iostream>
int main()
{
using namespace std;
cout << "Enter a number: ";
int nX;
cin >> nX;
if (nX > 10)
{
if (nX < 20)
cout << nX << "is between 10 and 20" << endl;
}
else // attached to outer if statement
cout << nX << "is less than 10" << endl;
return 0;
}
The use of a block tells the compiler that the else statement should attach to the if statement before the block. Without the block, the else statement would attach to the nearest unmatched if statement, which would be the inner if statement.
If statements are commonly used to do error checking. For example, to calculate a square root, the value passed to the square root function should be a non-negative number:
#include <iostream>
#include <cmath> // for sqrt()
void PrintSqrt(double dValue)
{
using namespace std;
if (dValue >= 0.0)
cout << "The square root of " << dValue << " is " << sqrt(dValue) << endl;
else
cout << "Error: " << dValue << " is negative" << endl;
}
If statements can also be used to do early returns, where a function returns control to the caller before the end of the function. In the following program, if the parameter nValue is negative, the function returns a symbolic constant or enumerated value error code to the caller right away.
int DoCalculation(int nValue)
{
// if nValue is a negative number
if (nValue < 0)
// early return an error code
return ERROR_NEGATIVE_NUMBER;
// Do calculations on nValue here
return nValue;
}
If statements are also commonly used to do simple math functionality, such as a min() or max() function that returns the minimum or maximum of it’s parameters:
int min(int nX, int nY)
{
if (nX > nY)
return nY;
else
return nX;
}
Note that this last function is so simple, it can also be written using the arithmetic if operator (?:):
int min(int nX, int nY)
{
return nX > nY ? nY : nX;
}
5.3 — Switch statements
|
Index
|
5.1 — Control flow introduction
|
5.3 — Switch statements
Index
5.1 — Control flow introduction
Hi, great website btw!
However, whenever i try to use a char variable in an if statement (e.g :
if(a = “Hello”)
cout << “Hello there”;
it does not compile correctly.
can anyone help? if so please email me on fight.the.purple@hotmail.co.uk or leave a comment
many thanks
First off, = is for assignment, not comparison. You would normally use == to do comparisons, except == doesn’t work on string literals (which is anything inside double quotes). Probably the best way is to declare your a variable as a std::string instead of a char. Then it will work as you expect. This is covered in lesson 6.6.
I’m trying to write a code, in which the user will enter a number, enter another number than write whether the 1st number was greater than, less than, or equal to, the 2nd number number. All numbers work, except when the 1st and 2nd numbers are both 0. In that case, it says nothing. My code is below; can you see the problem?
using namespace std;
cout <> nX;
cout << “You entered ” << nX << endl;
using namespace std;
cout <> nY;
cout << “You entered ” << nY < nY)
cout << nX << ” is greater than ” << nY << endl;
else if (nX < nY)
cout << nX << ” is less than ” << nY << endl;
else if (nX = nY)
cout << nX << ” is equal to ” << nY << endl;
Thanks.
Sorry, this is correct code.
using namespace std;
cout <> nX;
cout << “You entered ” << nX << endl;
using namespace std;
cout <> nY;
cout << “You entered ” << nY < nY)
cout << nX << ” is greater than ” << nY << endl;
else if (nX < nY)
cout << nX << ” is less than ” << nY << endl;
else if (nX = nY)
cout << nX << ” is equal to ” << nY << endl;