Why not always use compiler optimization?

前端 未结 9 1547
野性不改
野性不改 2020-12-08 02:17

One of the questions that I asked some time ago had undefined behavior, so compiler optimization was actually causing the program to break.

But if there is no undefi

9条回答
  •  隐瞒了意图╮
    2020-12-08 02:54

    There is an example, why sometimes is dangerous using optimization flag and our tests should cover most of the code to notice such an error.

    Using clang (because in gcc even without optimization flag, makes some iptimizations and the output is corrupted):

    File: a.cpp

    #include 
    
    int puts(const char *str) {
        fputs("Hello, world!\n", stdout);
        return 1;
    }
    
    int main() {
        printf("Goodbye!\n");
        return 0;
    }
    

    Without -Ox flag:

    > clang --output withoutOptimization a.cpp; ./withoutOptimization

    > Goodbye!

    With -Ox flag:

    > clang --output withO1 -O1 a.cpp; ./withO1

    > Hello, world!

提交回复
热议问题