General question about IF-ELSE bracket syntax


#1

I got a bit hung up because this is the correct bracket syntax:

if (blah) {
  do something;
}
else if (different blah) {
 do something different;
}
else {
 do something else;
}

Rather than:

if (blah) {
 do something;
 else if (different blah) {
   do something different;
   else {
     do something else;
   }
 }
}

That's slightly counter-intuitive to me, since the whole thing is essentially a unit. But they're being treated as separate. Is my thinking wrong?


#2

else is an optional second part:

if (condition) statement [else statement]

(square brackets to show it's optional)

Curly braces are used to group multiple statements into one, so that multiple statements can be used as the statement to run after if/else - that's why without braces only one line is included

And because an if-statement is a statement, one can be used as the statement for the else part, creating a "else if" which is nesting the if inside the else, but that's not how we prefer to write it as that would run off to the right for no benefit


#3

Oh. Yeah, I can make that make sense now. You want to execute the first bit and exit before deciding whether to continue. Thanks.


#4

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.