C++ logical operators


Free Web Hosting with Website Builder

This is a small tutorial/clarification on C++ logical operators & , | , && and ||.

Consider this C++ source file:

#include <iostream>
using namespace std;
 
int main(int argc, const char* argv[])
{
	//Proving conclusion:
	cout<<"Proving conclusion:\n";
	cout<< (0x7 & 0x2)<<endl;
	cout<< (0x6 | 0x1)<<endl;
	cout<< (0x7 && 0x0)<<endl;
	cout<< (0x7 || 0x0)<<endl;
	cout<< (0x2 && 0x1)<<endl;
	cout<< (0x2 || 0x1)<<endl;
}

Conclusion:

| and &: Are bitwise operators.
Operate on all the bits and return the comparison.

ex:
111 & 010 = 010
110 | 001 = 111

|| and &&: Are boolean logical operators.
Will evaluate if each value is true or false, then return the boolean operation's result.
ex:
111 && 000 = (1 AND 0) = 0
111 || 000 = (1 OR 0) = 1

beware:
10 && 01 = (1 AND 1) = 1
10 || 01 = (1 OR 1) = 1







Why are we here?
All text is available under the terms of the GNU Free Documentation License
This page is cache of Wikipedia. History