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

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

    Imagine such compiler exists. Let's also assume that for convenience it provides a library function that returns 1 if the passed function modifies a given variable and 0 when the function doesn't. Then what should this program print?

    int variable = 0;
    
    void f() {
        if (modifies_variable(f, variable)) {
            /* do nothing */
        } else {
            /* modify variable */
            variable = 1;
        }
    }
    
    int main(int argc, char **argv) {
        if (modifies_variable(f, variable)) {
            printf("Modifies variable\n");
        } else {
            printf("Does not modify variable\n");
        }
    
        return 0;
    }
    

提交回复
热议问题