Click here to Skip to main content
15,881,882 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
Is there "any" difference in performance between these two?
if(a() && b() && c() && d())
   doSomething();


if(a())
   if(b()) 
      if(c())
         if(d())
            doSomething();


What I have tried:

For example, if a() returns 0, would the first if statement continue to run b(), c(), and d()? Or will it behave similarly to the second nested if statement?
Before posting this code I've done some research and read an article on https://www.scaler.com/topics/c/nested-if-else-statement-in-c/.
Posted
Updated 18-Jul-22 0:16am
Comments
Rick York 18-Jul-22 11:15am    
The only real difference is there is no guarantee of the order of evaluation of the functions with && operators while there is with the nested conditional expressions.

They are the same, see Short-circuit evaluation - Wikipedia[^].
 
Share this answer
 
Comments
Patrice T 18-Jul-22 6:28am    
+5 The link I was looking for.
CPallini 18-Jul-22 6:30am    
Thank you.
I think it would depend on the compiler. I imagine GCC and clang would optimize the second form into the first form as long as there were no other statements between the ifs. You can check it yourself though (for any major compiler) using godbolt.org

Edit: Actually, upon reflection my guess is both result in the second form unless each method call in the test condition is an inline-able expression.
 
Share this answer
 
v2
Quote:
Is there "any" difference in performance between these two?

As far as I know, there is no difference.
Quote:
For example, if a() returns 0, would the first if statement continue to run b(), c(), and d()? Or will it behave similarly to the second nested if statement?

It is the standard practice of C language for last 40 years.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900