tl;dr: Is there a non-short circuit logical AND in C++ (similar to &&)?
I've got 2 functions that I want to call, and use the return values to figure out the return value of a 3rd composite function. The issue is that I always want both functions to evaluate (as they output log information about the state of the system)
IE:
bool Func1(int x, int y){
if( x > y){
cout << "ERROR- X > Y" << endl;
}
}
bool Func2(int z, int q){
if( q * 3 < z){
cout << "ERROR- Q < Z/3" << endl;
}
}
bool Func3(int x, int y, int z, int q){
return ( Func1(x, y) && Func2(z, q) );
}
Of course, the conditionals aren't quite that simple in the functions, and yes, I realize that I could use temporary variables to store the returns of the two functions and then do the "short-circuit" logic on the temporary variables, but I was wondering if there was an "elegant" language solution to keep the one-line return in Func3 while still getting the logging messages from both functions.
Summary of responses:
The "bitwise" operators | and & can be used to get the effect, but only if the return type is bool. I found no mention of this in the ANSI C++ spec. From what I can tell, this works because the "bool" is converted to an int (true = 1, false = 0), and then the bitwise operator is used, then it is converted back to a bool.
The Operators "+
" and "*
" can also be used. This is not mentioned in the ANSI C++ Spec, but probably works because of the same reason as above. "+
" give "or" because true is converted to 1, and then anything other than 0 is converted back to true. "*
" works for "and" because 1 (true) * 0 (false) == 0(false) and 1(true) * 1(true) == 1(true)
Both of these seem to rely on implicit type conversion to integer and then back to bool. Both of these will likely mess up whomever tries to maintain the code.
Other responses boil down to "Just use temporaries" or "Implement your own" which was not the question. The goal was to see if there was already an operator implemented in the C++ standard to do it.
The &
operator performs logical "and" operation for bool
operands and is not short circuited.
It's not a sequence point. You cannot rely on the order of evaluation of the operands. However, it's guaranteed that both operands are evaluated.
I do not recommend doing this. Using temporary variables is a better solution. Don't sacrifice readability for "clever code".