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 %Failed lesson reference, id 8349%, 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
5 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

42 comments to 7.2 — If statements and blocks

  • Note my comment. This program only prints something if user inputs a value greater than 10. But user was never asked to do so. If user inputs a value less than 10, program prints nothing and user can't figure out why it doesn't work.

    • Alex

      Yes, correct. This is something you wouldn't want to do in a real program, but the point of the program is to show how use of parenthesis disambiguates a dangling else case.

      You'll note in the next example we add an else case to the outer if statement.

  • Kanchana

    Dear Alex,
    It seems you are updating the whole tutorial. That's nice and thanx for that. I would like to make a little suggestion.
    If you could add a little note mentioning which parts were updated with the updated date that would be very much helpful for us.

    Thanx
    -Kanchana

  • Arnab

    I'm trying to write a code that that takes a no. from the user another no. from the user in the same line & any one of these operators (+ - * / %) beside the second no.& gives the result as output. How do I do this? Note: the user must be able to do this 5 times in a go.

    • Alex

      1) Since the user has to be able to do this 5 times, use a loop to allow the user to do this more than once. The loop can call a function.
      2) The function should ask the user for input, and then use an if statement (or switch statement) on the operator to give the result.

      This question is pretty similar to a question I asked in the chapter 2 comprehensive quiz, just with a loop so it executes more than one time.

  • Jake

    "Without the block, the else statement would attach to the nearest unmatched if statement..."

    Hey (not sure if you still check comments), but shouldn't the indentation of your 'else' statement(?) indicate which 'if' it belongs to? I understand the use of parentheses to aid in readability, but is that also the case for indentation in this regard?

  • Alam

    hello everyone
    i have a problem .it compiles even but never prints either of the code.just prints "press any key to continue".why so?

    #include
    #include // 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;
    }
    int main()
    {
    return 0;
    }

    • megablocks

      You created a function, but never called on it in your main() so nothing is being executed.
      Ex:
      #include
      int main()
      {
      double myValue = 2.0;
      PrintSqrt(myValue);
      return 0;
      }

Leave a Reply

You can use these HTML tags

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code class="" title="" data-url=""> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong> <pre class="" title="" data-url=""> <span class="" title="" data-url="">