0

take a look at the side effect of: while(run_i() && run_j()) vs while(run_i() & run_j()) in these two codes:

#include <iostream>

const int max = 5;

int i = -1;
int j = -1;

bool run_i()
{ i++; if(i < max) return true; else{ i=-1; return false;} }
bool run_j()
{ j++; if(j < max) return true; else{ j=-1; return false;} }

int main() 
{
  std::cout << "\n----bitwise &----\n";
  while(run_i() & run_j())
    std::cout << i << ',' << j << ' ';
  std::cout << "\n no side effect: \n";
  while(run_i() & run_j())
    std::cout << i << ',' << j << ' ';

  std::cout << "\n\n----logic &&----\n";
  while(run_i() && run_j())
    std::cout << i << ',' << j << ' ';
  std::cout << "\n side effect: \n";
  while(run_i() && run_j())
    std::cout << i << ',' << j << ' ';
  return 0;
}

output:

----bitwise &----
0,0 1,1 2,2 3,3 4,4 
 no side effect: 
0,0 1,1 2,2 3,3 4,4 

----logic &&----
0,0 1,1 2,2 3,3 4,4 
 side effect: 

I know that in while(run_i() && run_j()) when run_i() returns false, the compiler never bothers to evaluate run_j() so j stuck at 4, so in the next while loop it returns false at start and nothing is printed; I know this is the normal behavior, but I don't know if this is implementation specific or c++ forced specification, thus is my question. same question applies to the bitwise &. can I rely on its behavior in logic statement; meaning both sides of operands must be evaluated before logic condition is executed?

  • 1
    The part regarding `&&` is a duplicate of https://stackoverflow.com/questions/628526/is-short-circuiting-logical-operators-mandated-and-evaluation-order the other half is a duplicate of this one: https://stackoverflow.com/questions/54093421/is-it-guaranteed-that-bitwise-and-for-bool-does-not-short-circuit – fabian Nov 27 '22 at 13:35
  • If you just want to run both functions before `while` evaluation, try `do while` and execute both function and save their return values in the loop. Then evalutate both return values in `while` – Louis Go Nov 28 '22 at 04:59

0 Answers0