Can we change the value of an object defined with const through pointers?

前端 未结 10 1326
北恋
北恋 2020-11-22 10:49
#include 
int main()
{
    const int a = 12;
    int *p;
    p = &a;
    *p = 70;
}

Will it work?

10条回答
  •  萌比男神i
    2020-11-22 11:34

    Here the type of pointer p is int*, which is being assigned the value of type const int* (&a => address of a const int variable).

    Implicit cast eliminates the constness, though gcc throws a warning (please note this largely depends on the implementation).

    Since the pointer is not declared as a const, value can be changed using such pointer.

    if the pointer would be declared as const int* p = &a, you won't be able to do *p = 70.

提交回复
热议问题