简体   繁体   中英

Ambigious Behaviour of various c++ Compilers

When you do left shift of a -ve number on Leetcode it shows run time error as shown in the following screenshot leetcode compiler output

Now For the Same code on GeeksForGeeks IDE, it works well as shown below GFG IDE Output on same code

Same behaviour is observed when i submit the same code on the Code Blocks IDE.My Question is why is this ambiguity in the outputs . Please Help , i am very confused after reading various posts on left shifting in c++ on sof. Detailed Explanation will be Helpful.

There is "undefined behaviour" and there is "implementation defined behaviour" in C, C++, Objective-C.

"undefined behaviour" means anything can happen. Not just what you think is reasonable or what you expect, but anything . DON'T DO IT.

"implementation defined behaviour" means your compiler should document what it will do in this situation. You read the compiler documentation. Different compilers can do this in different ways.

This one (left shift of a negative number) is undefined behaviour. The rule: Don't do it. Don't complain about the result. If it bites you in the behind, you have only yourself to blame.

As others have answered, left-shifting a negative signed value is undefined behavior in C++ standard. Different compilers will treat undefined behavior differently.

For example, using compiler g++ (GCC) 9.2.0 for your code:

g++ test.cpp

will give no warning.

But you can use different option for the compiler, if you turn on all warning and treat warning as error in g++:

g++ -W -Wall -Werror test.cpp

The compiler will give error when compile the code.

Those websites may use different compilers & options underline their interface & thus, give different result. If you want to understand more about compiler, grab one and try with different options offline.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM