As with C, C + + uses Boolean expressions to simplify the evaluation (short-circuit evaluation). This means that once the true or False value of a Boolean expression is determined, even if some of the expressions are not tested, the Boolean expression stops the operation. For example:
char *p;
...
if ((p != 0) && (strlen(p) > 10)) ...
There's no need to worry. Strlen does not run correctly when P is empty, because if p does not equal 0 of the test fails, strlen will not be invoked. Same:
int rangeCheck(int index)
{
if ((index < lowerBound) || (index > upperBound)) ...
...
}
If index is less than lowerbound, it is not compared with upperbound.
The behavioral features of the time long ago have been repeatedly instilled in C and C + + programmers, so they all know the feature. And they also rely on short evaluation to write programs. For example, in the first code above, it is important to ensure that strlen is not invoked when p is a null pointer, because the C + + standard says (as the C standard says) to call strlen with a null pointer, the result is uncertain.
C + + allows you to customize && and | | Operator. The method is overloaded functions operator&& and operator| |, which you can overload in global overloads or in each class. However, if you want to use this method, you must know that you are dramatically changing the rules of the game. Because you replaced the short calculation with a functional modulation. That is, if you overload the operator && for you, the code is like this:
if (expression1 && expression2) ...
For the compiler, it is equivalent to one of the following code:
if (expression1.operator&&(expression2)) ...
// when operator&& is a
// member function
if (operator&&(expression1, expression2)) ...
// when operator&& is a
// global function
This seems to be no different, but the function invocation method is absolutely different from the short evaluation method. First, when the function is called, you need to compute all its arguments, so call the function functions operator&& and operator| | , two parameters need to be computed, in other words, a short calculation is not used. Second, the C + + language specification does not define the order in which the function parameters are computed, so there is no way to know which expression 1 and expression 2 are first computed. is completely contrary to the short calculation method with the order of calculation from left to right.