#include <iostream>
usingnamespace std;
int main()
{
int b = 0;
cout<<(b && b)<<endl;
return 0;
}
But after execution -
1 2 3 4
aryan@Aryan:~/Desktop/MyPrograms/C++/Tester$ c++ XML.cpp -o XML.out
aryan@Aryan:~/Desktop/MyPrograms/C++/Tester$ ./XML.out
0 //This is my executed CODE
aryan@Aryan:~/Desktop/MyPrograms/C++/Tester$
But according to me answer must be 1 (or true) as 0 = 0. But computer is saying that 0 is not equal to 0?
This is due to the way that boolean logic operates. An integer can be implicitly converted to a bool, where 0 = false and everything else is true. The && operator takes two bools, which means this is what you are doing:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
int main() {
// int b = 0;
bool b = false;
std::cout << std::boolalpha;
// what you are doing:
std::cout << (b && b) << std::endl;
std::cout << (b == b) << std::endl;
// which is equal to
std::cout << (false && false) << std::endl;
std::cout << (false == false) << std::endl;
return 0;
}
false
true
false
true
As @cire pointed out, you are getting confused between the && operator (comparing if two results are both true) and the == operator (checking to see if two results are the same).
The result of the expression a==5 && c==7 will be either true or false. I don't see what bits have to do with it.
nomijigr wrote:
but if u want to perform AND logic u need & operator.. c=a&b;//result will be number of bits of a or number of bits of b..
This will result in c having a bit pattern where all of the bits that are set in both a and b are set in c. If one wants to do a logical and one should use &&, not & which is the bitwise and operator.