Why is it allowed to overwrite a const variable using a pointer to it using memcpy?

后端 未结 4 395
难免孤独
难免孤独 2021-01-21 04:19

Why is it allowed to change a const variable using a pointer to it with memcpy?

This code:

const int i=5;
int j = 0;
memcpy(&j, &i, sizeof(int));         


        
4条回答
  •  轻奢々
    轻奢々 (楼主)
    2021-01-21 04:57

    The reason why is because the C language allows any pointer type to be implicitly casted to/from the type void*. It is designed that way because void pointers are used for generic programming.

    So a C compiler is not allowed to stop your code from compiling, even though the program invokes undefined behavior in this case. A good compiler will however give a warning as soon as you implicitly try to cast away a const qualifier.

    C++ has "stronger typing" than C, meaning that it would require an explicit cast of the pointer type for this code to compile. This is one flaw of the C language that C++ actually fixed.

提交回复
热议问题