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?