Search code examples
coptimization

compile with GCC -O2 option generate different program


I heard that C compiler with/without optimization option may generate different program(compiling the program with optimizations causes it to behave differently), but I never encountered such case. Anyone can give simple example to show this?


Solution

  • For gcc 4.4.4, this differs with -O0 and -O2

    void foo(int i) {
      foo(i+1);
    }
    
    main() {
      foo(0);
    }
    

    With optimizations this loops forever. Without optimizations, it crashes (stack overflow!)

    Other and more realistic variants would typically be dependent on timing, vulnerable to float exactness variations, or depending on undefined behavior (uninitialized variables, heap/stack layout)