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
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With