Search

7.3 — Common if statement problems

This lesson is a continuation of lesson 7.2 -- If statements and blocks. In this lesson, we’ll take a look at some common problems that occur when using if statements.

Nested if statements and the dangling else problem

It is possible to nest if statements within other if statements:

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 if statements, it is a good idea to enclose the inner statement within a block. Here is the above program written without ambiguity:

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:

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.

Flattening nested if statements

Nested if statements can often be flattened by either restructuring the logic or by using logical operators (covered in lesson 5.7 -- Logical operators). Code that is less nested is less error prone.

For example, the above example can be flattened as follows:

Here’s another example that uses logical operators to check multiple conditions within a single if statement:

Null statements

A null statement is a statement that consists of just a semicolon:

Null statements do nothing. They are typically used when the language requires a statement to exist but the programmer doesn’t need one. For readability, null statements are typically placed on their own lines.

We’ll see examples of intentional null statements later in this chapter, when we cover loops. Null statements are rarely intentionally used with if statements. However, they can unintentionally cause problems for new (or careless) programmers. Consider the following snippet:

In the above snippet, the programmer accidentally put a semicolon on the end of the if statement (a common mistake since semicolons end many statements). This unassuming error compiles fine, and causes the snippet to execute as if it had been written like this:

Warning

Be careful not to “terminate” your if statement with a semicolon, otherwise your conditional statement(s) will execute unconditionally (even if they are inside a block).

Operator== vs Operator= inside the conditional

Inside your conditional, you should be using operator== when testing for equality, not operator= (which is assignment). Consider the following program:

This program will compile and run, but will produce the wrong result in some cases:

Enter 0 or 1: 0
You entered 1

In fact, this program will always produce the result You entered 1. This happens because x = 0 first assigns the value 0 to x, then evaluates to the value of x, which is now 0, which is Boolean false. Since the conditional is always false, the else statement always executes.


7.4 -- Switch statement basics
Index
7.2 -- If statements and blocks

22 comments to 7.3 — Common if statement problems

  • ItsOkayTryAgain

    A little confused at the part ,"else statement is paired up with the last unmatched if statement in the same block.Thus the else is matched up with the inner if statement."

    Isn't the inner if in an implicit block? In my head the outer if and the else are in the same block. (。•́︿•̀。)

    • Lesommeil

      There is all implicit block represents.

      int main()
      {

          std::cout << "Enter a number: ";
          int x{};
          std::cin >> x;

          if (x >= 10) // outer if statement
          {
              // it is bad coding style to nest if statements this way
              if (x <= 20) // inner if statement
              {
                  std::cout << x << "is between 10 and 20\n";
              }
              // which if statement does this else belong to?
              else
              {
                  std::cout << x << "is greater than 20\n";
              }

          }
          return 0;
      }

  • John

    How can assign a variable inside if statement? For example I want to assign 10 to x if y==1 and 20 to x if y==2 or for another examples. How can I use if statement for this purpose.

  • Chayim

    How is this code

    using one = for logical equals and not two == like it’s supposed to be? and how does two logics work  at once >= ?

    • frog

      as I understand it,
      >= and <= are single operators. You can think of them this way:

      (x >= y) is the same as (x > y || x == y)
      (x <= y) is the same as (x < y || x == y)

  • Chayim

    Why does "if (x = 0)" become Boolean false and does not remain as int 0 assigned to x  that will not have any function ?

  • AutomaticP

    Wouldn't it be a better practice to explicitly state the range of values that passes the condition, so that

    becomes

    and maybe even explicitly stating the remaining range in the last 'else'

    ?

    • nascardriver

      The most common cause of errors is the developer. Don't let the developer make mistakes. Redundant code is asking for trouble.

    • Sukhmander

      In this case your checking x>=10 which is already true and implied if x is not smaller than 10.This has performance penality(if you check all obvious conditions you are reducing performance) and if you think readability is the issue you can just write comment in this case

  • IndentationMan

    Indentation is slightly off on line 13 of the last code example in the "Nested if statements and the dangling else problem" section.

    Also, right below that, the lesson says "Without the block, the else statement would attach to the nearest unmatched if statement, which would be the inner if statement." In the example above it, isn't the inner if statement already matched by an else?

    • Anubhav Chauhan

      Yes, I was wondering the same. The inner if statement is already matched by the inner else. Even if we remove the blocks, the outer else should be paired up with the last unmatched if which in this case is the outer if, because the inner if is already matched by an else

  • J34NP3T3R

    is it better to practice if statements this way ;
    is it readable or also a bad practice ?

    if ( x == 1 )
    { std::cout << "it is ONE"; }
    else
    { std::cout << "it is NOT ONE"; }

    so that if i add more lines of codes in either statement i could just do a carriage return

    if ( x == 1 )
    {
        std::cout << "it is ONE";
        // more code
    }
    else
    { std::cout << "it is NOT ONE"; }

  • Philippe Martens

    The first example under ‘Using logical operators inside the conditional’ is wrong. It’ll display « 30 is less than 10 », for example.

  • Waldo Lemmer

    Section "Using logical operators inside the conditional":
    Last snippet, lines 9-11:
    [code]
        std::cout << "Enter another integer: ";
        int y; // Line 10; should be initialized for consistency with other examples
        std::cin >> y;
    [code]

Leave a Comment

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