Why doesn't GCC optimize this call to printf?

后端 未结 3 2036
萌比男神i
萌比男神i 2021-01-17 10:12
#include 
int main(void) { 
    int i;
    scanf(\"%d\", &i);
    if(i != 30) { return(0); } 
    printf(\"i is equal to %d\\n\", i);
}

3条回答
  •  借酒劲吻你
    2021-01-17 10:40

    Modern compilers are quite clever, but not clever enough to foresee the output using logic. In this case, it's quite simple for human programmers to optimise this code, but this task is too hard for machines. In fact, predicting the output of a program without running it is impossible for programs (gcc for example). For proof, see halting problem.

    Anyway, you don't expect all programs without inputs to be optimised to several puts() statements, so it's perfectly reasonable for GCC not to optimise this code containing one scanf() statement.


    However, this does not mean compilers cannot or should not be optimised to generate more optimised executive files. Although it's impossible to predict the result all programs, it's perfectly possible and hopeful to improve many of them.

提交回复
热议问题