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

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

    There are multiple avenues to explaining this, one of which is the Halting Problem:

    In computability theory, the halting problem can be stated as follows: "Given a description of an arbitrary computer program, decide whether the program finishes running or continues to run forever". This is equivalent to the problem of deciding, given a program and an input, whether the program will eventually halt when run with that input, or will run forever.

    Alan Turing proved in 1936 that a general algorithm to solve the halting problem for all possible program-input pairs cannot exist.

    If I write a program that looks like this:

    do tons of complex stuff
    if (condition on result of complex stuff)
    {
        change value of x
    }
    else
    {
        do not change value of x
    }
    

    Does the value of x change? To determine this, you would first have to determine whether the do tons of complex stuff part causes the condition to fire - or even more basic, whether it halts. That's something the compiler can't do.

提交回复
热议问题