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

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

    As soon as a function calls another function that the compiler doesn't "see" the source of, it either has to assume that the variable is changed, or things may well go wrong further below. For example, say we have this in "foo.cpp":

     void foo(int& x)
     {
        ifstream f("f.dat", ifstream::binary);
        f.read((char *)&x, sizeof(x));
     }
    

    and we have this in "bar.cpp":

    void bar(int& x)
    {
      foo(x);
    }
    

    How can the compiler "know" that x is not changing (or IS changing, more appropriately) in bar?

    I'm sure we can come up with something more complex, if this isn't complex enough.

提交回复
热议问题