Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"if" block without curly braces makes subsequent "else if" nested

Tags:

AFAIK, if an "if" block is not provided the curly braces then only 1 statement is considered inside it. e.g.

if(..)   statement_1;   statement_2; 

Irrespective of tabs, only statement_1 is considered inside the if block.

Following code doesn't get along with that:

int main () {   if(false)  // outer - if     if(false)  // nested - if       cout << "false false\n";   else if(true)     cout << "true\n"; } 

Above code doesn't print anything. It should have printed "true".
It appears as of the else if is automatically nested inside the outer if block. g++ -Wall issues warning, but that is not the question here. Once you put the curly braces, everything goes fine as expected.

Why such different behavior ?
[GCC demo: without braces and with braces].

like image 880
iammilind Avatar asked Jul 31 '12 06:07

iammilind


People also ask

What happens in a IF statement where there is no curly braces?

One-line statement Well if there is only one statement to execute after if condition then using curly braces or not doesn't make it different. Without curly braces only first statement consider in scope so statement after if condition will get executed even if there is no curly braces.

Do you need curly braces for if statements Java?

Java has a "feature" which allows you to omit curly brackets when writing if statements, for loops, or while loops containing only a single statement. You should never use this feature – always include curly brackets. The reason for this is because omitting curly brackets increases your chances of writing buggy code.

Is there is only one statement inside the loop can we skip the curly braces?

So we can omit curly braces only there is a single statement under if-else or loop. Here in both of the cases, the Line1 is in the if block but Line2 is not in the if block. So if the condition fails, or it satisfies the Line2 will be executed always.


1 Answers

The behaviour isn’t actually different, it’s entirely consistent: the whole inner if block – including else if – is considered as one block.

This is a classical ambiguity in parsing, known as the “dangling-else problem”: there are two valid ways of parsing this when the grammar is written down in the normal BNF:

Either the trailing else is part of the outer block, or of the inner block.

Most languages resolve the ambiguity by (arbitrarily) deciding that blocks are matched greedily by the parser – i.e. the else [if] is assigned to the closest if.

like image 182
Konrad Rudolph Avatar answered Oct 21 '22 10:10

Konrad Rudolph