dangling else statement

hi,
I am not knowing dangling else statement.What is it?How to avoid it?Please explain me with example.

Last edited on
Every else statement has to follow an if statement. The whole purpose of an 'else' is to be executed if the previous 'if' was not executed. So if there is no previous 'if', then having an 'else' makes no sense.

A dangling else is one that has no previous if.


Example:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
if(foo < 5)
{
    // this block executed if foo is less than 5
}
else  // <- OK, immediately follows an 'if' block
{
    // this block executed if foo is NOT less than 5
}



else // <- dangling 'else'.  This will be a compiler error because there is no previous 'if'
{
}
Hi Disch, the word Dangling else is very new word, you have given the very nice explanation.

for more information about the control structures refer
http://www.cpptutorials.com/2014/11/control-structures-conditional.html
@Disch, else can also follow else if. Not sure if this was implied
well an 'else if' is an 'else' followed by an 'if'. It's not anything special, it's just shorthand:

1
2
3
4
5
6
7
8
9
10
11
if(foo) {} 
else if(bar) {}
else {}

// is the same as
if(foo)
else
{
    if(bar) {}
    else {}
}


As with all control statements, the braces are optional for 1-liners immediately following the statement.


But yeah, you're right.
Last edited on
Topic archived. No new replies allowed.