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

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

Will it work?

相关标签:
10条回答
  • 2020-11-22 11:24

    This code contains a constraint violation:

    const int a = 12;
    int *p;
    p = &a;
    

    The constraint violated is C11 6.5.16.1/1 "Simple assignment"; if both operands are pointers then the type pointed to by the left must have all the qualifiers of the type pointed to by the right. (And the types, sans qualifiers, must be compatible).

    So the constraint is violated because &a has type const int *, which has const as a qualifier; but that qualifier does not appear in the type of p which is int *.

    The compiler must emit a diagnostic and might not generate an executable. The behaviour of any executable would be completely undefined, since the program does not comply with the rules of the language.

    0 讨论(0)
  • 2020-11-22 11:27

    It does indeed work with gcc. It didn't like it though:

    test.c:6: warning: assignment discards qualifiers from pointer target type

    But the value did change when executed. I won't point out the obvious no-no...

    0 讨论(0)
  • 2020-11-22 11:31

    Bad, BAD idea.

    Also, the behavior is platform- and implementation-specific. If you're running on a platform where the constant is stored in non-writable memory, this obviously won't work.

    And, why on earth would you want to? Either update the constant in your source, or make it a variable.

    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题