I’ve done some reading of previous posts and I’ve learned some things but want to verify how some loops are working. In reading, am I right in understanding that “true” has higher precedence than “false”? For instance:
/.../
return (true || false);
will return “true” (regardless of order)?
If I have a boolean recursive function that calls 3 variations of itself…all I need is for one version to return true for the whole funct to return true, correct? The function below creates it’s stack frame, then the return call creates 3 more stack frames and runs through the calls, then if one returns true the whole funct returns true because true has precedence over false… Is this assumption correct?
Ie:
/* This function is taking a given weight and seeing if it can be offset by available
* weights. Depending on what weights are available, the weights can be directly opposed
* to "weight" (opposite side of scale) or added to... The recursive calls will either all
* return false, all return true, or a variation thereof. All that I can is that if one
* branch returns true, the overall function returns true...
*/
bool CanMeasure(int weight, std::vector<int> &availableWeights, int index = 0)
{
/.../
// the below can return all true, all false, or some variation thereof...
return (CanMeasure(weight + availableWeights[index], availableWeights, index + 1) ||
CanMeasure(weight - availableWeights[index], availableWeights, index + 1) ||
CanMeasure(weight, availableWeights, index + 1));
}
Thanks guys!
Yes (it will return
trueregardless of order). The conditions in theorare evaluated from left to right, and when the firsttrueis stumbled upon, the whole condition returnstrue.In your example:
not all conditions are necesarily evaluated. If the first one evaluates to
true, the others will not execute, and the function will just returntrue.It’s called short-circuiting.
Let’s take a look at some dissasembled code:
In this example,
foo()andgoo()are both functions returning bool.The instruction
tells the runtime to jump out of the conditional if
foo()evaluated to true.This code is not optimized, so it’s not an optimization feature.