Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to prove the order of execution of a nested else statement?

Please note that it's not a question on how else binds and how the scope stretches. Also, please note, that it's not a question on if we should or shouldn't use curly braces.

Regard the following nested conditional statement.

if(alpha)
  if(beta)
    AlphaAndBeta();
  else
    AlphaNotBeta();

Personally, even if I'm a big believer of removing any redundant parenthesis, I'd suggest usage of curly braces in this case to make it abundantly clear that the else statement is a part of the inner condition, which can be tricky to see, especially if some smart-donkey starts horsing around with the indentation like so.

if(alpha)
  if(beta)
    AlphaAndBeta();
else
  AlphaNotBeta();

However, I'd like to have a handy reference to where the behavior is described. I've looked at the language definition on MSDN but haven't found the exact spot. It needs to be super-ultra-clearly stated how the else bind to its if (and doesn't necessarily have to be MS's official site).

Where can I find the page, please?

like image 231
Konrad Viltersten Avatar asked Dec 10 '22 20:12

Konrad Viltersten


2 Answers

This is documented in the C# specification, section 8.7.1 - The if statement:

An else part is associated with the lexically nearest preceding if that is allowed by the syntax. Thus, an if statement of the form

if (x) if (y) F(); else G();

is equivalent to

if (x) {
   if (y) {
      F();
   }
   else {
      G();
   }
}
like image 79
Lasse V. Karlsen Avatar answered May 21 '23 02:05

Lasse V. Karlsen


Here's one resource, MSDN:

The statement or statements in the then-statement and the else-statement can be of any kind, including another if statement nested inside the original if statement. In nested if statements, each else clause belongs to the last if that doesn’t have a corresponding else.

like image 21
Tim Schmelter Avatar answered May 21 '23 01:05

Tim Schmelter