Is there a difference between i==0 and 0==i?

后端 未结 8 1370
我在风中等你
我在风中等你 2020-11-27 22:51

First code:

  if(i==0) {// do instructions here}

Second code:

  if(0==i) { // do instructions here }

What

相关标签:
8条回答
  • 2020-11-27 23:18

    Functionally, there is no difference.
    Some developers prefer writing the second format to avoid assignment typos(in case you miss a =), so that compiler warns of the typo.
    The second is famously known as Yoda Condition.

    Yoda Condition

    I say there is no difference because, you cannot guard yourself against every minuscule detail and rely on compiler to cry out aloud for you.If you intend to write a == you should expect yourself to write a == and not a =.
    Using the second format just leads to some obscure non-readable code.
    Also, most of the mainstream compilers warn of the assignment instead of equality typo by emitting an warning once you enable all the warnings(which you should anyways).

    0 讨论(0)
  • 2020-11-27 23:19

    no difference, some people prefer the second one to catch the common mistake of doing assignment (=) instead of equality test (==)

    0 = i would fail at compilation

    0 讨论(0)
  • 2020-11-27 23:25

    Yep they are same as far as C# is concerned. For more complex situations visit A==B vs B==A, What are the differences

    0 讨论(0)
  • 2020-11-27 23:31

    For C++, it's possible, though unlikely, that there could be a difference. It depends upon what i's type is. e.g.

    struct Foo
    {
        int x;
    };
    
    bool operator==(Foo lhs, int rhs)
    {
        return lhs.x == rhs;
    }
    
    bool operator==(int lhs, Foo rhs)
    {
        std::cout << "Hi!";
        return true;
    }
    

    Someone who writes code like that should of course be shot.

    0 讨论(0)
  • 2020-11-27 23:33

    Functionally, they are the same in C; I'm not sure about other languages where ugly things like operator overloading come into play.

    Stylistically, the latter is extremely counter-intuitive and personally I find it extremely ugly. The point is to get the compiler to throw an error when you accidentally write = instead of ==, but good compilers have an option to warn you about this anyway so it's unnecessary.

    0 讨论(0)
  • 2020-11-27 23:38

    The second version is supposed to be safer.

    In case you forget one equal sign, it does not change the value of i to zero.

    0 讨论(0)
提交回复
热议问题