Question:
c++ is this an exmple of nested if else statement? if yes...?
?
2016-04-07 01:21:31 UTC
c++ is this an exmple of nested if else statement? if yes,how many levels of nesting is it?
if (condition)
{statement}
else if (condition)
{statement}
else if (condition)
{statement}
else if (condition)
{statement}
else()
{statement}
Three answers:
husoski
2016-04-07 01:56:19 UTC
Technically, yes. Each if statement after the first is entirely inside the else part of the previous if statement. It is the *only* statement within that else part, so it doesn't need braces.



However, that pattern is used in C-based languages to get the same effect as having an "elsif" or "elif" keyword that other languages like Ada and Python have, so each if part (and the final else part) is indented the same as the first if part. It's such a common pattern that programmers don't think of each addition if statement as nested, but rather part of a longer chain.



The formal definition of the language, though, treats that as:



if (condition)

  {statement}

else

  if (condition)

    {statement}

   else

     if (condition)

       {statement}

     else

       if (condition)

         {statement}

       else

         {statement}



Like I said, that's not how programmers usually think of it that way. With good reason. The "properly indented" version above is harder to read and a pain in the butt to re-indent when a test is added in the middle.



The "if/else if/else chain" is an example of a programming idiom. It's not really part of the language definition, but can be used consistently as if it were.
Undisclosed
2016-04-07 05:18:47 UTC
It isn't. "Nested" means one within the other. That means something like:



If(condition){ if(conditionNested){statementNested} }



has one level of nesting. What you posted is an "If Else" statement.
Chris
2016-04-07 01:25:26 UTC
nested means that {statement} contains its own if block.


This content was originally posted on Y! Answers, a Q&A website that shut down in 2021.
Loading...