C++: the evil runtime error: left shift of negative value, reason and how to solve
Someone may encounter an error:   left shift of negative value, when you (me too!) wrote the code as follows:\n\nclass Solution {\npublic:\n    int getSum(int a
Someone may encounter an error:   left shift of negative value, when you (me too!) wrote the code as follows:\n```\nclass Solution {\npublic:\n    int getSum(int a, int b) {\n        int trigger = a & b;\n        int ret = a ^ b;\n        while(trigger)\n        {\n            int temp = trigger<<1; //problem!\n            trigger = temp & ret;\n            ret ^= temp;\n        }\n        return ret;\n    }\n};\n```\nIt happens when your input a (or b) is a negative number, and you may saw some solutions like:\n\n```\nclass Solution {\npublic:\n    int getSum(int a, int b) {\n        int trigger = a & b;\n        int ret = a ^ b;\n        while(trigger)\n        {\n            int temp = (trigger & 0xffffffff)<<1; //not a problem anymore!\n            trigger = temp & ret;\n            ret ^= temp;\n        }\n        return ret;\n    }\n};\n```\nI was confused at fist. I searched some materials and looked others\' comments, and summarize the reason here (hope it can help someone like me):\nwhen a is a **signed int** and **negative**, it seems that\n```\na << 1\n```\nis not well defined in C++ standard, even you may pass your code in Visual Studio or some other IDE. I think this is why the first version does not work in LeetCode.\n\nHowever, the second version works because \'**0xffffffff**\' (8 fs) is an **unsigned int**. Note that **0x0fffffff** (7 fs) is an **int**.  When we have \n```\ntrigger & 0xfffffff\n```\nwe get an **unsigned int**, and the left bit shift of the **unsigned int** is defined by filling zeros at the tail. In the end, we convert this **unsigned int** to **int**, by **int temp =**. In this way, the error is avoided.\n\nAn better alternative is to replace **int temp = (trigger & 0xffffffff)<<1;** with\n```\nint temp = (unsigned int)trigger << 1;\n```\nif you do not like to implicitly assume that the size of int is four bytes (another evil fact that the size of int is not fixed in C++).
[]