Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nested If (x) checks - Better way to write this?

Tags:

c++

c

There are places where I check for valid pointers before I perform an operation with them; these checks can be nested pretty deeply sometimes.

For example, I have

if (a)
{
  if (a->b())
  {
    if (a->b()->c())
    {
      a->b()->c()->DoSomething();
    } 
  }
}

I really don't like the look of this. Is there a way to turn this into something more readable? Ideally,

if (a && a->b() && a->b()->c() )
{
 ...
}

would be great, but obviously would not work.

EDIT - nvm the example that I put up DOES work as everybody has pointed out. I did test it out to see if this works, but there was a bug in my code in my test. duh!

like image 625
Will Avatar asked May 20 '10 16:05

Will


People also ask

Is there a better way than nested IF statements Excel?

Alternatives to nested IF in Excel To test multiple conditions and return different values based on the results of those tests, you can use the CHOOSE function instead of nested IFs. Build a reference table and a use VLOOKUP with approximate match as shown in this example: VLOOKUP instead of nested IF in Excel.

How do you write nested IF?

We nest an IF function by setting value_if_false to IF B2 greater than or equal to 80, return B. We use additional nested IF functions to test for C, D, and F grades. I am copying the formula. In this formula, we must test B2 greater than or equal to 90 first, and then, B2 greater than or equal to 80, and so on.

Should you avoid nested IF statements?

Avoid using nested if-else statements. Keep the code linear and straightforward. Utilize creating functions/methods. Compare it when we try to use an if-else statement that is nested and that does not utilize the power of the return statement, We get this (Code 1.4).

What is the correct way to write the IF function?

Use the IF function, one of the logical functions, to return one value if a condition is true and another value if it's false. For example: =IF(A2>B2,"Over Budget","OK") =IF(A2=B2,B4-A4,"")


2 Answers

Why would the latter not work?

In C, && is a short-circuit operator, so it is evaluated from left to right, and if any evaluation is false, evaluation stops.

In fact, you could write:

a && a->b() && a->b()->c() && a->b()->c()->DoSomething();
like image 66
WhirlWind Avatar answered Sep 28 '22 05:09

WhirlWind


Quoting from K&R1:

Expressions connected by && or || are evaluated from left to right, and it is guaranteed that evaluation will stop as soon as the truth or falsehood is known.

Therefore the latter example will work perfectly, as WhirlWind has noted.


1The C Programming Language, Second Edition, Page 21.

like image 23
Daniel Vassallo Avatar answered Sep 28 '22 06:09

Daniel Vassallo