I have a for loop that I want to write without curly braces (perfectionism and laziness). Will this chain of conditions work in a loop or not?

for(int i = 0; i < mass.count; i++) if(a < b) { } else if (a > b) { } else { } 
  • And why do you think that will not happen? - Pavel Mayorov
  • 3
    It will, of course. And how do you think will be performed? if every iteration of the loop is checked, and else only after it? - VladD
  • @VladD Good, thanks - Minebot
  • @VladD And if instead of a cycle to put if? Will it work too? If in the nested condition to leave only if, then the next else will be nested or not? - Minebot
  • if there can be a problem of the "higher else" - the compiler does not look at the formatting :) If you really want very much without parentheses, put the loop body into a separate function / method. - KoVadim

1 answer 1

Yes, counts as one sentence.

You can submit the original if

 if(a < b) { } else if (a > b) { } else { } 

as

 if(a < b) вложенный-оператор else вложенный-оператор 

where the first nested-operator is the empty block operator {} (empty block), and the second nested operator is, in turn, the if statement if (a > b) { } else { }

As written in the C # Programming Language book with the participation of Anders Hejlsberg as author (Chapter 8. Operators)

"The nested operator can be used inside other operators, and the nesting level is not limited."

Perhaps there are some restrictions on nesting in the language specification, however, they are not significant for real programs.

  • 2
    speak ms vc ++ was a bug with nesting more than 127 levels. - pavel
  • yes it's true :) - KoVadim
  • Oh my God! I will not survive that my 128 nested loops cannot be written in one piece ... code =) - rdorn
  • @KoVadim But seriously, is this really a problem or did the maniacs just check the strength of the compiler? - rdorn
  • It then turns out that it is impossible to gobno much :) - Minebot