Any difference between !a and a==0?

Any difference between !a and a==0?

 
  !a

 
  a==0


seems to have the same result.
! means opposite if a is equal to zero it will become one.

== means check if both values are equal. if they are both equal it will result to one.
Yes. It may work for fundamental data types, but if you go for classess, one may overload both ! and == operators, so it may not work as you intend.
they typically have the same result only during comparisons , like in loops or if statements , other wise , "!" operator returns the complement of the number a. And of course you cannot use "==" other than during comparison statements. One more thing , the above may be true only if the operators are not overloaded.
closed account (28poGNh0)
You think they are the same , just because they return a boolean value(1 or 0) prof

1
2
3
4
5
6
7
8
9
10
11
12
# include <iostream>
using namespace std;

int main()
{
    int nbr = 1;

    cout << (nbr == 0) << endl;
    cout << !nbr << endl;
    
    return 0;
}


but they are different

== : is a relational and equality operator that evaluates comparaison between two expressions

! : is a logical operator performs boolean operations

some exp

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
# include <iostream>
using namespace std;

int main()
{
    int nbr = 1;

    if(nbr == 1)// comparaision between nbr and 1
    {
        while(!(nbr == 5))
        {
            cout << "The expression " << nbr << " == 5 is false" << endl;
            nbr++;
        }
        cout << "The expression " << nbr << " == 5 is true" << endl;
        cout << "but !(" << nbr << " == 5) is false that\'s why while loop ended" << endl;
    }

    return 0;
}


hope that helps
Thanks a lot. ^_^
But I think in this example
while(!(nbr == 5))
can also be replaced with
while((nbr == 5)==0)
to some extent, there is still no difference.
Last edited on
Both expressions are equivalent if a is an integer or a boolean.
Topic archived. No new replies allowed.