Why are there two const in the variable statement?

Asked

Viewed 90 times

9

I can do it:

const int* const objeto = &x;

Why are there two const? What is the function of each?

1 answer

10


They determine the ability to change the value of an object in memory. Remember that pointer types have two distinct parts, one is the pointer itself that is stored in the variable, and the object that is pointed by the pointer.

The const leftmost prevents the value of the object from being exchanged after initialized. The const rightmost prevents the pointer from being switched, that is, the variable points to another different object and is potentially a new value.

I made examples and commented on the codes that would not work to compile.

#include <stdio.h>

int main(void) {
    int x1 = 1, x2 = 2, x3 = 3, x4 = 4;
    int* p1;
    p1 = &x1;
    *p1 = 10;
    const int* p2;
    p2 = &x2;
    //*p2 = 20; //tentativa de trocar o valor do objeto
    int* const p3 = &x3;
    //p3 = &x1; //tentativa de trocar o ponteiro para o objeto
    *p3 = 30;
    const int* const p4 = &x4;
    //p4 = &x2; //tentativa de trocar o valor do objeto
    //*p4 = 40; //tentativa de trocar o ponteiro para o objeto
    printf("%d %d %d %d", *p1, *p2, *p3, *p4);
}

Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.

It is interesting to understand about What is the difference between declaration and definition?.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.