The difference in the two ways of checking equality i == 0 vs 0 == i in C ++

I am browsing a huge code base in C ++. The author used syntax 0==ito verify equality. I have been programming in C ++ for several years; I have always used the syntax i==0.

Do the former have advantages over the latter? Or is it just a personal preference?

+4
source share
3 answers

The first has the advantage that it prevents the programmer from accidentally giving up the equal sign.

if (i = 0)

The above is legitimate and sets ito zero and is false (since zero is considered false).

if (0 = i)

The above is illegal in all contexts.

if (i = 0), , .

+10

0==i "yoda ". , , , .

, , , 0=i .

0=i, i=0.

1672. , ( , ), , ( ), .

+11

For a prime integer, as others have explained, it 0 == iminimizes the risk of creating a typo.

However, if you have overloaded operator==, then it 0 == imay be a mistake:

class X
{
public:
    X(int x) : _x(x) {};
    bool operator==(int y) { return _x == y; }
private:
    int _x;
};

....

X x(0);
if (x == 0) // OK
    ;
if (0 == x) // error
    ;
+3
source

All Articles