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

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

    Really surprised that there isn't an answer that using the halting problem directly! There's a very straightforward reduction from this problem to the halting problem.

    Imagine that the compiler could tell whether or not a function changed the value of a variable. Then it would certainly be able to tell whether the following function changes the value of y or not, assuming that the value of x can be tracked in all the calls throughout the rest of the program:

    foo(int x){
       if(x)
           y=1;
    }
    

    Now, for any program we like, let's rewrite it as:

    int y;
    main(){
        int x;
        ...
        run the program normally
        ...
        foo(x);
    }
    

    Notice that, if, and only if, our program changes the value of y, does it then terminate - foo() is the last thing it does before exiting. This means we've solved the halting problem!

    What the above reduction shows us is that the problem of determining whether a variable's value changes is at least as hard as the halting problem. The halting problem is known to be incomputable, so this one must be also.

提交回复
热议问题