Search code examples
c++c++14

Is writing else statement at the last mandatory in if-else ladder in C++?


I have always seen that at the end of an if-else ladder in C++, the bottom else statement is always present.

if (condition1) {
  doA();
} else if (condition2) {
  doB();
} else if (condition3) {
  doC();
} else {
  noConditionsMet();
}

Is it necessary to do this syntax-wise? Or i can also write code as shown below i.e without using the last else statement ?

if (condition1) {
  doA();
} else if (condition2) {
  doB();
} else if (condition3) {
  doC();
}

I know that the below code also gets run successfully. But I just wanted to confirm by asking this in the forum.


Solution

  • It's optional, and the "ladder" is an illusion.

    The syntax of a conditional statement is

    if (condition) 
        statement 
    else 
        statement
    

    where the else branch is optional.
    Whether the else branch happens to be another conditional doesn't matter.

    Note that your "ladder" is equivalent to

    if (condition1) {
      doA();
    } else {
        if (condition2) {
          doB();
        } else {
            if (condition3) {
                doC();
            } else {
                noConditionsMet();
            }
        }
    }
    

    which makes it clearer that it's not a "ladder", just nested statements.
    It's just that you can leave out the "block braces" when a branch consists of a single statement.