Why is it impossible to build a compiler that can determine if a C++ function will change the value of a particular variable?

后端 未结 13 912
感动是毒
感动是毒 2021-01-30 02:01

I read this line in a book:

It is provably impossible to build a compiler that can actually determine whether or not a C++ function will change the val

13条回答
  •  刺人心
    刺人心 (楼主)
    2021-01-30 02:31

    I don't think it's necessary to invoke the halting problem to explain that you can't algorithmically know at compile time whether a given function will modify a certain variable or not.

    Instead, it's sufficient to point out that a function's behavior often depends on run-time conditions, which the compiler can't know about in advance. E.g.

    int y;
    
    int main(int argc, char *argv[]) {
       if (argc > 2) y++;
    }
    

    How could the compiler predict with certainty whether y will be modified?

提交回复
热议问题