This article describes the C + + short-circuit evaluation (logic and, logic or), share for everyone to reference. The specific methods are analyzed as follows:
1, logic or short circuit
First look at the following code:
#include <iostream>
using namespace std;
int main ()
{
int a = 1;
cout << "a =" << a <<endl;
true | | (a=0);
cout << "a =" << a <<endl;
}
The results of the operation are as follows:
The logical or expressive form is as follows:
expression1 | | Exexpression2
This uses logic or, because of a logical or short-circuit, expression1 is true, then the expression2 (i.e. (a=0)) is no longer evaluated, and the entire expression evaluates to True, so the value of a is still 1, unchanged.
2. Logic and Short Circuit
First look at the following code:
#include <iostream>
using namespace std;
int main ()
{
int a = 1;
cout << "a =" << a <<endl;
False && (a=3);
cout << "a =" << a <<endl;
}
The results of the operation are as follows:
The logical and expressive forms are as follows:
Expression1 && Exexpression2
The above code uses logic and, due to logic and short-circuit, expression1 is false, then the expression2 is no longer evaluated, the entire result is false, so the value of a has not changed.
3, Application examples
Here is an example of a post on CSDN (http://topic.csdn.net/u/20121011/10/c7e0a805-b4e2-44db-9d71-455f5f851240.html):
Without the If statement, no assembly, how to make the product of two is always less than or equal to 255?
When you look at a post, you will find that there are many ways, such as the simplest conditional expression:
result = ((a*b) > 255)? 255:a*b;
This is the first to be proposed, but as if the landlord does not agree, then try the following two ways:
To short-circuit with logic or:
BOOL TMP = (result = A*b) < 255) | | (result=255);
Short Circuit with logic:
BOOL TMP = (result = a*b) >= 255) && (result=255);
The complete code is as follows:
#include <iostream>
using namespace std;
int main ()
{
int a,b,result;
while (true)
{
cin>>a>>b;
Result = ((a*b) > 255)? 255:a*b; BOOL TMP = (result = A*b) < 255) | | (result=255);
BOOL TMP = (result = a*b) >= 255) && (result=255);
cout<<result<<endl;
}
}
The operation effect is as follows:
I hope this article will help you with the C + + program design.