Short-Circuit Evaluation

◀ Exceed Integer Limits▶ cin.peek() and cin.putback()
Amazon Short-circuit evaluation simply means that in a condition, control evaluates from left to right only the necessary expressions to know whether the condition is true or false. Short circuit evaluation is a common part of the compiler’s optimization steps.

The following is a sample program:
#include<iostream>
using namespace std;

int main() {
	int a[3]={1,2,3};
	int b=4;
	if(b==4 || a[1000]==0)
		cout<<"Cheers, Kathy!"<<endl;
	if(!(b==3 && a[1000]==0))
		cout<<"Cheers, Sheree!"<<endl;
	return 0;
}
When you compile and run this program, you will see that both if statements are taken. The first one is taken because b equals 4 and no matter what a[1000] is, the value of the condition must be true. The second one is taken because b==3 is false and no matter what a[1000] is, && makes the condition false, which is made true by !. As we can see, 1000 is way over the bounds of the int array, but it is ignored.

Now let’s run the following program:
#include<iostream>
using namespace std;

int main() {
	int a[3]={1,2,3};
	int b=4;
	if(a[1000]==0 || b==4)
		cout<<"Greg is one of the very best"<<endl;
	if(!(a[1000]==0 && b==3))
		cout<<"and so is Ian"<<endl;
	return 0;
}
The two statements inside the if statements are reversed in order. Now the compiler sees a[1000]==0 first and needs to evaluate its truth first. Most likely this will result in a segmentation fault because a[1000] is way beyond its bounds.

As we can see, the feature of short-circuit evaluations can reduce the program’s running time. Take this behavior into consideration whenever you write a condition.
Next let’s look at several interesting functions of the cin library!
◀ Exceed Integer Limits▶ cin.peek() and cin.putback()

fShare
Questions? Let me know!