Is optimization dangerous? [closed]-Collection of common programming errors

If optimization (by your compiler) is breaking your code while you believe it should not,

  • your code is not following the language standard, or
  • your compiler is broken, and you should upgrade it.

Language standards are quite complex to understand (in particular because not everything is specified, and some things are explicitly left unspecified or implementation specific). Read about undefined behavior

Compilers are in practice tested a big lot, and you should often first suspect your own code, and only after be sure your code is right (and fully standard conforming) suspect the compiler (in other words, compiler optimization bugs -where the generated code is wrong– are quite rare in practice).

Be sure to upgrade your compiler to a recent version. For GCC it is today (december 2013) 4.8.2; don’t blame GCC if you are using a 4.4 or 3.6 GCC compiler, these ancient versions are not maintained anymore!

In practice, enable all warnings and debugging info when developping your code (e.g. compile with gcc -Wall -g at least, perhaps even with -Wextra). When you are sure of the quality of your code, compile it with optimizations and warnings (e.g. gcc -Wall -g -O2) and test it a lot.

In practice, profile the execution of your tests and (when possible) focus your efforts on the hot code (the one taking most of the CPU time).