Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ Speed and Logical Flow

I was wondering if there are any speed advantage to doing case B vs case A (or vice versa) in the following:

bool test1(){
// Check something, return true/false
}
bool test2(){
// Check something, return true/false
}

Case A

if(test1() && test2()){
    //execute XYZ
}

Case B

if(test1()){
  if(test2()){
      //execute XYZ
  }
}

I mean, if the routines involved in test1() and test2() take some time to execute, then intuitively some people may think that Case B may run faster, since test2() would only get executed if test 1 is true, or is the compiler smart enough to determine, within the logical sequence of Case A, that as soon as test1(...) fails, then test2(...) need not be checked?

Perhaps the above are equivalent, can someone let me know...

like image 253
Nicholas Hamilton Avatar asked Dec 09 '22 01:12

Nicholas Hamilton


1 Answers

is the compiler smart enough to determine yes it is, this is called Short-circuit evaluation, and works with &&, || and ? operators (unless you overload them), as described in the standard in paragraphs 5.14, 5.15 and 5.16.

like image 188
SingerOfTheFall Avatar answered Dec 27 '22 22:12

SingerOfTheFall