Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Stepping into an else statement after entering the if statement due to curlys

This example of the code works properly, e.g. enters first if, drops out after not meeting 2nd if.

if (i < _commandList.Count)
{
    if (output.Length > 0)
        Console.WriteLine(output);
}
else
    Console.WriteLine("Invalid Command.");

I initially had coded it as this, which doesn't work. It enters the first if, does not meet the 2nd if as expected, but then enters the else statement and does the writeline.

if (i < _commandList.Count)
    if (output.Length > 0)
        Console.WriteLine(output);
else
    Console.WriteLine("Invalid Command.");

Why does the second code block not work the same as the first block? Since only a single line of code is below the first statement, I thought it was permissible to not have the {}.

For reference, the stack frame is:

_commandList.Count = 1
output.Length = 0
i = 0
like image 506
jlipstate Avatar asked Nov 27 '22 02:11

jlipstate


1 Answers

This is the "dangling else" problem: the else always belongs to the closest if, regardless of the indentation.

Your first snippet uses curly braces to tell the compiler that the else belongs to the top if, not to the inner one. The second snippet lets the compiler decide; the compiler applies the nearest if rule, and attaches the else to the inner if.

like image 125
Sergey Kalinichenko Avatar answered Dec 19 '22 05:12

Sergey Kalinichenko