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

后端 未结 13 1021
感动是毒
感动是毒 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:44

    It can be done and compilers are doing it all the time for some functions, this is for instance a trivial optimisation for simple inline accessors or many pure functions.

    What is impossible is to know it in the general case.

    Whenever there is a system call or a function call coming from another module, or a call to a potentially overriden method, anything could happen, included hostile takeover from some hacker's use of a stack overflow to change an unrelated variable.

    However you should use const, avoid globals, prefer references to pointers, avoid reusing variables for unrelated tasks, etc. that will makes the compiler's life easier when performing aggressive optimisations.

提交回复
热议问题