Which one will execute faster, if (flag==0) or if (0==flag)?

后端 未结 16 840
灰色年华
灰色年华 2020-11-30 17:12

Interview question: Which one will execute faster, if (flag==0) or if (0==flag)? Why?

16条回答
  •  我在风中等你
    2020-11-30 17:51

    Which one's fast depends on which version of == you are using. Here's a snippet that uses 2 possible implementations of ==, and depending on whether you choose to call x == 0 or 0 == x one of the 2 is selected.

    If you are just using a POD this really shouldn't matter when it comes to speed.

    #include 
    using namespace std;
    
    class x { 
      public:
      bool operator==(int x) { cout << "hello\n"; return 0; }
      friend bool operator==(int x, const x& a) { cout << "world\n"; return 0; } 
    };
    
    int main()
    { 
       x x1;
       //int m = 0;
       int k = (x1 == 0);
       int j = (0 == x1);
    }
    

提交回复
热议问题