Search

7.2 — If statements and blocks

The first category of control flow statements we’ll talk about are the conditional statements. A conditional statement is a statement that specifies whether some associated statement(s) should be executed or not.

C++ supports two basic kind of conditionals: if statements (which we introduced in lesson 4.10 -- Introduction to if statements, and will talk about further here) and switch statements (which we’ll cover in a couple of lessons).

Quick if-statement recap

The most basic kind of conditional statement in C++ is the if statement. An if statement takes the form:

if (condition)
    true_statement;

or with an optional else statement:

if (condition)
    true_statement;
else
    false_statement;

If the condition evaluates to true, the true_statement executes. If the condition evaluates to false and the optional else statement exists, the false_statement executes.

Here is a simple program that uses an if statement with the optional else statement:

This program works just like you’d expect:

Enter a number: 15
15 is greater than 10
Enter a number: 4
4 is not greater than 10

If or else with multiple conditional statements

New programmers often try something like this:

However, consider the following run of the program:

Enter your height (in cm): 180
You are tall enough to ride.
Too bad!

This program doesn’t work as expected because the true_statement and false_statement can only be a single statement. The indentation is deceiving us here -- the above program executes as if it had been written as follows:

This makes it clearer that “Too bad!” will always execute.

However, it’s common to want to execute multiple statements based on some condition. To do so, we can use a compound statement (block):

Remember that blocks are treated as a single statement, so this now works as expected:

Enter your height (in cm): 180
You are tall enough to ride.
Enter your height (in cm): 130
You are not tall enough to ride.
Too bad!

To block or not to block single statements

There is debate within the programmer community as to whether single statements following an if or else should be explicitly enclosed in blocks or not.

There are two reasons typically given as rationale for doing so. First, consider the following snippet:

Now let’s say we’re in a hurry and modify this program to add another ability:

Oops, we’ve just allowed minors to gamble. Have fun in jail!

Second, it can make programs more difficult to debug. Let’s say we have the following snippet:

Let’s say we suspect something is wrong with the addBeerToCart() function, so we comment it out:

Now we’ve made checkout() conditional, which we certainly didn’t intend.

Neither of these problems occur if you always use blocks after an if or else statement.

The best argument for not using blocks around single statements is that adding blocks makes you able to see less of your code at one time by spacing it out vertically, which makes your code less readable and can lead to other, more serious mistakes.

The community seems to be more in favor of always using blocks than not, though this recommendation certainly isn’t ubiquitous.

Best practice

Consider putting single statements associated with an if or else in blocks.

A middle-ground alternative is to put single-lines on the same line as the if or else:

This avoids both of the above downsides mentioned above at some minor cost to readability.

Implicit blocks

If the programmer does not declare a block in the statement portion of an if statement or else statement, the compiler will implicitly declare one. Thus:

if (condition)
    true_statement;
else
    false_statement;

is actually the equivalent of:

if (condition)
{
    true_statement;
}
else
{
    false_statement;
}

Most of the time, this doesn’t matter. However, new programmers sometimes try to do something like this:

This won’t compile, with the compiler generating an error that identifier x isn’t defined. This is because the above example is the equivalent of:

In this context, it’s clearer that variable x has block scope and is destroyed at the end of the block. By the time we get to the std::cout line, x doesn’t exist.

We’ll continue our exploration of if statements in the next lesson.


7.3 -- Common if statement problems
Index
7.1 -- Control flow introduction

167 comments to 7.2 — If statements and blocks

  • Waldo Lemmer

    Great lesson! I look forward to the rest of this chapter.

    1. Section "Quick if-statement recap":

    > This program works just like you’d expect:

    5 should be 4 (or vice versa)

    2.
    > Now we’ve made checkout() conditional, which we certainly didn’t intend.
    Oh, wow. I've always thought that if-statements execute the next line, not the next statement. I forgot C++ ignores whitespace.

    • Alex

      Fixed! (Also fixed the other lessons based on your feedback). Thank you!

    • SuperNoob

      Hey man, you do competitive programming?

        • SuperNoob

          So I guess you are learning cpp for:

          1. CS subject
          2. knowledge thirst
          3. system programming

          Which one is it?

          • Waldo Lemmer

            I don't really know yet. I'm 16

            • SuperNoob

              Oh okay, carry on :D Is it your first language or you have experience on another language too?

              • Waldo Lemmer

                I have some experience with other languages, but I didn't get far with any of them, and I forgot everything.

                learncpp.com is by far the best tutorial I've encountered, and the only one that I'll complete from start to finish

                • SuperNoob

                  Agreed. This is by far the best website for c++ that I have encountered. I tried some well known books before. But didn'm find them amusing enough.

                  You know I know advanced python. Even wrote games using that (lol, game with python!) But running speed of python is terrible especially for performance critical stuffs like games. So I switched to c++.

                  • Waldo Lemmer

                    > I tried some well known books before

                    I'm not a fan of books, because
                    1. They get outdated
                    2. They often contain mistakes that don't get fixed
                    3. They provide no way to ask the author questions, and to view others' questions and answers.
                    This website satisfies all three of those requirements :)

                    > running speed of python is terrible
                    > So I switched to c++

                    One of the main reasons why I want c++ to be the first language I fully understand. It's fast, easy to use and a lot of languages stem from it (actually C, but C doesn't have OOP)

                    Happy learning :D

                    • SuperNoob

                      Yeah, pretty good points. Which chapter are you in now?

                    • Aulya

                      Valid points. But I still recommend people to use textbooks.
                      I started from Bjarne's principles and it was the first time I enjoyed learning a programming language. What I like from the book is the presentation of the material is full and well organized. And I can feel the difficulty level increasing. Unlike many books that too educational purposes, the explanations for each section always attract curiosity and fun! :D I take advantage of this for anything I need to know other than practical needs. The rest, from learncpp. I can say that the two of them complement each other well.

                  • Forhad Rahman

                    Unity or Unreal? (¬‿¬)
                    I am also learning C++ currently for game dev. Though C# was a good choice, but it's mainly focused in Microsoft Ecosystem.
                    C++ is the complete beast & it can be used in almost anything. After all, performance matters (◍•ᴗ•◍)

  • yeokaiwei

    In the previous chapter S4.5-Enumerated Types

    "Best practice

    Don’t assign specific values to your enumerators."

    It's confusing.

    Which rule do we follow?

    • TigerTM

      Like pretty much all programming. It depends. As a general rule you shouldnt assign specific values, but there are some cases where it makes sense. When in doubt follow generalized rules unless you have a good reason not to.

      Using an enum class in this case makes sense, it keeps things together all in one place, but an equally valid solution would have been to store them as constants in a namespace. This is just less work and serves the purpose of the example well.

      Chosing to store it as an enum instead of a constant means that it can be passed as a variable instead of just an int value, which can be really helpful sometimes. You inherently get more information with an enum variable than you do with just an int.

    • nascardriver

      No specific values should have been assigned in this example, I've updated the lesson. Thanks for pointing it out!
      What you quoted is a "Best practice", and that's also what @TigerTM described. Follow the "Best practice" unless you have a good reason not to. For specific enumerator values, a good reason to diverge from the best practice can be that the values must not change during updates or that the values are exposed to the user. Both these scenarios can be met with error code enums. If error code 42 meant "file not found" in program version 1.2.1, it should still have the same meaning in version 1.3.4. By assigning specific values, you're preventing the programmer from inserting an enumerator between others, thus shifting all values.
      Since the enumerator values aren't exposed in this example, there's no need for specific values to be used.

  • allright

    it allows multiple init statements of same type but not different types or am i missing a point here

  • Andreas Krug

    Shouldn't the first line of the "Using logical operators with if statements" chapter end with "(covered in section 5.7 -- Logical operators)" instead of "(covered in section 3.6 -- logical operators)"?

Leave a Comment

Put all code inside code tags: [code]your code here[/code]