3 ms·
Here is a fun demonstration of undefined behaviour that someone showed me recently: http://ideone.com/LsEUPa http://ideone.com/LsEUPa
by detrino 12y ago
Here is a fun demonstration of undefined behaviour that someone showed me recently: http://ideone.com/LsEUPa http://ideone.com/LsEUPa
- anon4 12y agoGCC seems helpful here $ g++ -O2 -Wall -Werror -o asdf asdf.cpp asdf.cpp: In function ‘int main(int, char**)’: asdf.cpp:9:29: error: iteration 3u invokes undefined behavior [-Werror=aggressive-loop-optimizations] std::cout << (i*1000000000) << std::endl; ^ asdf.cpp:7:2: note: containing loop for (int i = 0; i < 4; ++i) ^ cc1plus: all warnings being treated as errors Clang compiles it but doesn't produce an endless loop. You can get defined behaviour by casting to unsigned: std::cout << (int)(((unsigned) i) * 1000000000U) << std::endl; Which seems like a good rule of thumb: when working on x86 and x64 and doing things with numbers that you think might overflow, do it with unsigned and cast back to what you need.