Const variable changed with pointer in C

前端 未结 5 934
心在旅途
心在旅途 2020-12-02 02:40

The variable i is declared const but still I am able to change the value with a pointer to the memory location to it. How is it possible?

int ma         


        
5条回答
  •  眼角桃花
    2020-12-02 03:06

    It's not the attempt to modify i that causes your program's behavior to be undefined, it's the initialization of ip.

    const int i = 11;
    int *ip = &i;
    

    &i is of type const int*. ip is of type int*. Attempting to initialize an int* with a const int* value is a constraint violation. A conforming implementation is requires to issue a diagnostic; once it's done that, it may or may not reject the translation unit. If it accepts it, the C standard says nothing about the resulting program's behavior.

    Compilers that accept such things typically generate code equivalent to a conversion from const int* to int*, making the declaration effectively equivalent to:

    int *ip = (int*)&i;
    

    but the language doesn't require this behavior.

    Don't ignore warnings.

    (Note that with the cast, the code doesn't violate a constraint; then the behavior of the following

    *ip = 100;
    

    is undefined because it attempts to modify a const-qualified object.)

    gcc in particular has a lot of cases where diagnostics for constraint violations are handled (by default) as warnings rather than fatal errors. I personally dislike that about gcc; it lets through too much bad code.

    (Your program's behavior is also undefined because you call printf without a visible declaration; add #include . And int main() should be int main(void).)

提交回复
热议问题