Transition to the else statement after entering the if statement due to curls

This sample code works correctly, for example. comes first if, falls after the 2nd does not occur, if.

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

I originally encoded it like this, which does not work. It enters the first if, does not match the second, if expected, but then enters the else statement and writes.

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

Why doesn't the second code block work the same as the first block? Since only one line of code is below the first statement, I considered it permissible not to be {}.

For reference, the stack frame:

_commandList.Count = 1
output.Length = 0
i = 0
+4
source share
3 answers

" else": else , .

, , else if, . ; if else if.

+22

dasblinkenlight . , , munch. : , , .

if :

if ( ) statement-statement

if ( Boolean-expression ) result-statement else

,

if (c) if (d) E(); else F();

:

  • , .
  • , if. if, .
  • , .
  • . , , .
  • if. , if.
  • . else? ! if .
  • else, ... if. if.
  • else? . if .

: .

+12

By specifying curly braces, you tell the compiler that else comes with the first, if instead of the second, if.

+2
source

Source: https://habr.com/ru/post/1528169/


All Articles