&& Logic operator

Plz take a look at code -

1
2
3
4
5
6
7
8
9
10
11
#include <iostream>
using namespace 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?
Last edited on
&& is not ==.

0 && 0 is false.
0 && 1 is false.
1 && 0 is false.
1 && 1 is true.

Both must be true in order for the expression to be true.
but in 0 && 0, both are in order.
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).
Last edited on
there is a difference..as far as i understood, u r confusing && and &...with eachother...

if u need to compare(answer is either true or false,boolean) u need &&
e.g
if(a==5 && c==7)//result will be 1 bit..
{.......}

but if u want to perform AND logic u need & operator..
e.g

c=a&b;//result will be number of bits of a or number of bits of b..

hope it helps..stay blessed
Last edited on
nomijigr wrote:
if(a==5 && c==7)//result will be 1 bit..

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.
sry cire...i mixed c++ with the one used in embedded systems...its like that there...
Topic archived. No new replies allowed.