CommonLounge Archive

C++: If Statements and Comments

September 11, 2018

In the last tutorial, you learnt about C++: Variables and Getting Input. In this tutorial, you’ll learn about if-statements, using which you can do certain things only if certain conditions are met. In plain English, if-statements correspond to “Do this; then do that.” or “If this condition is true, perform this action; otherwise, do that action.”

A good way to visualize if-statements is flow charts. If-statements represent the yes / no questions in the flowchart below.

Before getting into if-statements, you’ll first learn how to compare things in C++ using comparing operators and Boolean data type (values true and false) in much depth, which we learnt in previous tutorials. At the end of the lesson, you’ll also see comments, which are useful for making your code more readable and easy to follow.

Compare things

A big part of programming involves comparing things. What’s the easiest thing to compare? Numbers, of course. Let’s see how that works:

cout << (5 > 2) << endl;     // Output - 1 (true)
cout << (3 < 1) << endl;     // Output - 0 (false)
cout << (5 > 2 * 2) << endl; // Output - 1 (true)
cout << (1 == 1) << endl;    // Output - 1 (true)
cout << (5 != 2) << endl;    // Output - 1 (true)

Do you wonder why we put two equal signs == next to each other to compare if numbers are equal? We use a single = for assigning values to variables. You always, always need to put two of them – ==– if you want to check if things are equal to each other. We can also check that things are unequal to each other. For that, we use the symbol !=, as shown in the example above.

Why does the code output 1 instead of true and 0 instead of false? Recall what we said about converting bool to int in the first tutorial:

If a boolean is converted to an integer, true becomes 1 and false becomes 0. If an integer is converted to a boolean, 0 becomes false and any other non-zero value becomes true.

That is the reason why the earlier code output is 1 when the expression evaluates to true and it’s 0 when the expression is false.

If you want C++ to print true and false instead of 1 and 0, you can use the boolalpha keyword. Here’s an example:

#include <iostream>
using namespace std;
int main() {
    cout << boolalpha; // program will print "true" and "false" from now
    cout << false << endl;   // output - false
    cout << (5 > 3) << endl; // output - true
    return 0;
}

Not only can C++ compare numbers, but it can also compare method results.

string a = "Commonlounge";
string b = "David";
cout << (a.length() > 10) << endl; // Output - 1 (true)
cout << (b.length() > 10) << endl; // Output - 0 (false)

Nice, huh?

Let’s give C++ two more tasks:

cout << (6 >= 12 / 2) << endl; // Output - 1 (true)
cout << (3 <= 2) << endl;      // Output - 0 (false)

We’ve seen > and <, but what do >= and <= mean? Read them like this:

  • x > y means: x is greater than y
  • x < y means: x is less than y
  • x <= y means: x is less than or equal to y
  • x >= y means: x is greater than or equal to y

We’ve summarized the list of comparison operators in C++ in a table at the end of the article.

Logical Operators

C++ has logical operators which allows you to combine multiple comparisons. You can give C++ as many numbers to compare as you want, and it will give you an answer! The following are the logical operators:

  • and operator (&&) – both comparisons have to be true in order for the whole expression to be true.
  • or operator (||) – at-least one of the comparisons has to be true in order for the whole expression to be true
  • not operator (!) - inverts the value of the expression

Try these:

cout << ( 6 > 2 && 2 < 3 ) << endl; // Output - 1 (true)
cout << ( 3 > 2 && 2 < 1 ) << endl; // Output - 0 (false)
cout << ( 3 > 2 || 2 < 1 ) << endl; // Output - 1 (true)
cout << !( 3 > 2 ) << endl;         // Output - 0 (false)

You can give C ++ as many numbers to compare as you want, and it will give you an answer! Pretty smart, right?


As we’ve done with examples before, let’s see the step-by-step evaluation of one of the above expressions to make sure everything is crystal clear.

3 > 2 && 2 < 1
=> true && 2 < 1
=> true && false
=> false

Boolean

We learnt briefly about Boolean data type in the first tutorial, but let’s dive deeper.

As we already know that there are only two Boolean values:

  • true
  • false

But for C++ to understand this, you need to always write it as true (all the letters should be lowercase). True, TRUE, and tRUE won’t work – only true is correct. (The same applies to false as well, of course.)

Booleans can be variables, too! See here:

bool a = true;
cout << a << endl;
// Output - 1 (true)

You can also directly assign the value of a comparison:

bool a = 2 > 5;
cout << a << endl;
// Output - 0 (false)

Practice and have fun with Booleans by trying to run the following commands:

  • true && true
  • false && true
  • true && 1 == 1
  • 1 != 2

Congrats! Booleans are one of the coolest features in programming, and you just learned how to use them!

If … else if … else

Lots of things in code should be executed only when given conditions are met. That’s why C++ has something called if statements.

Let’s try to make C++ print “It works!” by using if statement. Write the below code and run it:

if (3 > 2) {
    cout << "It works!" << endl;
}
// Output - It works!

Some notes:

The if-condition (in this case 3 > 2) must be enclosed in parenthesis - ( and ).

The body, i.e. statements that should execute if condition is true must be enclosed in curly braces - { and }. The only exception to this is when the body has exactly one statement - in that case, the curly braces can be omitted.

if (5 > 2)
    cout << "Hello" << endl;
// Output - Hello

What if a condition isn’t True?

In the previous example, code was executed only when the condition was true. But C++ also has else and else if statements:

if (5 > 2) {
    cout << "5 is indeed greater than 2" << endl;
} 
else {
    cout << "5 is not greater than 2" << endl;
}
// Output - 5 is indeed greater than 2

If 2 were a greater number than 5, then the second command would be executed. Let’s see how else if statements work:

string name = "Dave";
if (name == "Commonlounge") {
    cout << "Hey Commonlounge!" << endl;
} 
else if (name == "Dave") {
    cout << "Hey Dave!" << endl;
} 
else {
    cout << "Hey anonymous!" << endl;
}
// Output - Hey Dave!

See what happened there? else if lets you add extra conditions that run if the previous conditions fail.

You can add as many else if statements as you like after your initial if statement. For example:

int volume = 57;
if (volume < 20) {
    cout << "It's kinda quiet." << endl;
}
else if (volume >=20 && volume < 40) {
    cout << "It's nice for background music" << endl;
}
else if (volume >= 40 && volume < 60) {
    cout << "Perfect, I can hear all the details" << endl;
}
else if (volume >= 60 && volume < 80) {
    cout << "Nice for parties" << endl;
}
else if (volume >= 80 && volume < 100) {
    cout << "A bit loud!" << endl;
}
else {
    cout << "My ears are hurting!" << endl;
}
// Output - Perfect, I can hear all the details

Note that in chained if … else if … else statements, only the first condition that is met gets executed. As soon as the first condition is met, none of future else (or else if) conditions will be considered. Hence, the earlier code could be written more concisely as:

int volume = 57;
if (volume < 20) {
    cout << "It's kinda quiet." << endl;
}
else if (volume < 40) {
    cout << "It's nice for background music" << endl;
}
else if (volume < 60) {
    cout << "Perfect, I can hear all the details" << endl;
}
else if (volume < 80) {
    cout << "Nice for parties" << endl;
}
else if (volume < 100) {
    cout << "A bit loud!" << endl;
}
else {
    cout << "My ears are hurting!" << endl;
}
// Output - Perfect, I can hear all the details

We’re making use of the fact that, when we compare volume < 60 (for example), all the previous conditions must have been false. This automatically implies that volume >= 40 (since the first two conditions were false). The code might be slightly harder to read, but it is equivalent to the previous one.

Comments

Comments are lines beginning with //. You can write whatever you want after the // and C++ will ignore it. Comments can make your code easier for other people to understand. You can also write multi-line comments using /* and */.

Let’s see how that looks:

int volume = 100;
// change the volume if it's too loud or too quiet
if (volume < 20 or volume > 80) {
    volume = 50;
    cout << "That's better!" << endl;
}
cout << volume << endl;
/* Output:
That's better!
50
*/

Anything written between /* and */ is ignored by the compiler. Whereas for //, the compiler only ignores things written on the same line (after //).

You don’t need to write a comment for every line of code, but they are useful for explaining why your code is doing something, or providing a summary when it’s doing something complex.

Summary

In the last few exercises you learned about:

  • comparing things – in C++ you can compare things by using >, >=, ==, <=, < and the &&, || and ! operators.
  • Boolean – a type of object that can only have one of two values: true or false
  • if … else if … else – statements that allow you to execute code only when certain conditions are met.
  • comments - lines that C++ won’t run which let you document your code

Appendix: List of Comparison Operators

The following is a list of all comparison operations supported by C++.

Operator | Example | Result | Description 
---------|---------|--------|--------------------------------
   ==    | 4 == 5  | false  | is equal to
   !=    | 4 != 5  | true   | is not equal to
   >     | 4 > 5   | false  | is greater than
   <     | 4 < 5   | true   | is less than 
   >=    | 4 >= 5  | false  | is greater than or equal to
   <=    | 4 <= 5  | true   | is less than or equal to

Appendix: List of Boolean Operators

The following is a list of all boolean operations supported by C++.

Operator  | Examples        | Result | Description 
==========|=================|========|====================================
 && (and) | 3 < 4 && 5 < 4  | false  | true if both values are true
          | 3 < 4 && 5 > 4  | true   | 
----------|-----------------|--------|------------------------------------
 || (or)  | 3 < 4 || 5 < 4  | true   | true if at-least one value is true
          | 3 > 4 || 5 < 4  | false  | 
----------|-----------------|--------|------------------------------------
 !  (not) | !false          | true   | inverts the value 
          | !true           | false  | 

© 2016-2022. All rights reserved.