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

后端 未结 13 768
感动是毒
感动是毒 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条回答
  •  慢半拍i
    慢半拍i (楼主)
    2021-01-30 02:44

    Even if a variable is declared const, doesn't mean some badly written code can overwrite it.

    //   g++ -o foo foo.cc
    
    #include 
    void const_func(const int&a, int* b)
    {
       b[0] = 2;
       b[1] = 2;
    }
    
    int main() {
       int a = 1;
       int b = 3;
    
       std::cout << a << std::endl;
       const_func(a,&b);
       std::cout << a << std::endl;
    }
    

    output:

    1
    2
    

提交回复
热议问题