-2

I use the following codes to illustrate my question:

if( a== 0)
{
   if(b==0)
    {
         if(c == 0)
         {
            //
          }
     }

}

vs

if((a==0)&&(b==0)&&(c==0))
{

}

The first code fragment is the same with the second on when it comes from functionalities. The second one is more concise and easy to understand. I just wondering after code compilation whether both code fragments perform the same. Will the second runs faster? Here, we assume there are many comparions. For example

if((a==0)&&....(y==0)&&(z==0))
{

}  
feelfree
  • 11,175
  • 20
  • 96
  • 167
  • 1
    why not look at the compiler emitted code, or run a test to see which is faster – pm100 Dec 15 '16 at 17:19
  • 2
    It most likely won't matter one iota for any real application compiled with an optimizing compiler. If things such as these (trivialities) are what you are worried about, then I suspect you are either playing with toy example programs or you have *much* bigger problems. – Jesper Juhl Dec 15 '16 at 17:22
  • Just a note on style: you don't need the extra parentheses in `if (a==0&&b==0&c==0)`. – Pete Becker Dec 15 '16 at 17:28

1 Answers1

3

I just wondering after code compilation whether both code fragments perform the same.

There most likely won't be any significant performance difference - chained builtin logical operators are short-circuited, which means that...

if(a && b) { }

...is semantically equivalent to...

if(a) { if (b) { } } 

Regardless, the discussion in this question ("Can the C compiler optimizer violate short-circuiting and reorder memory accesses for operands in a logical-AND expression?") points out that compilers have some optimization freedom even with short-circuited logical expressions.

Therefore, the only true way of making sure that the performance is unchanged is measuring and looking at the generated assembly.


Regarding "style", I think this is a purely subjective issue.

Community
  • 1
  • 1
Vittorio Romeo
  • 90,666
  • 33
  • 258
  • 416