C/C++ has a couple of different ways to perform selections. We’re going to start looking at some of these.
As with most languages, C./C++ has a Boolean data type, called bool. This can be used directly with your conditions, or separately to store data.
Relational Operators
Since we will need to compare values, C/C++ gives us several different ways to make comparisons, each of which will result in a Boolean result.
Operator | Name | Example | Result |
---|---|---|---|
< | Less Than | 5 < 3 | false |
<= | Less Than or Equal To | 3 <= 3 | true |
> | Greater Than | 5 > 3 | true |
>= | Greater Than or Equal To | 4 >= 3 | true |
== | Equal To | 3 == 4 | false |
!= | Not Equal To | 3 != 4 | true |
Notice that the equality symbol is actually two equals sign.
If Statements
C++ if statements are similar to if statements in Python, but there are a few minor differences. The general form is below:
if (<condition statement>)
{
// true block
}
The braces are technically only needed if your true block is more than one line of code, however, it is usually smart to always use them. Your true block is normally indented, to make it easier to read, but it is not required like it is in Python.
Your condition must be enclosed by parentheses, and there is no colon at the end like there is in Python.
Let’s look at some samples:
if ( radius > 30)
{
cout << "That radius seems too big for our needs?" << endl;
}
if ( age < 21 )
{
cout << "You cannot purchase this until you are 21." << endl;
}
Else Statements
If you want to do something different when the condition block is false, you can use the else
block. This works very similar to the else block in languages like JavaScript or Python.
The general form is below:
if (<condition statement>)
{
// true block
}
else
{
// false/else block
}
Notice, like with the if statement, the braces are optional, but highly suggested. They are required if you have more than one line of code in your block.
Additionally, while indenting is not required, it is suggested, to make your code easier to read and edit.
if ( age < 18 )
{
cout << "You are too young to vote." << endl;
}
else
{
cout << "You are old enough to vote. Please exercise this right." << endl;
}
Introduction to C++ Selections was originally found on Access 2 Learn