Why are there two const variables in the variable declaration?

8

I can do this:

const int* const objeto = &x;

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

    
asked by anonymous 15.03.2017 / 12:25

1 answer

9

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

The leftmost% with% prevents the value of the object from being changed after initialization. The% plus rightmost% prevents the pointer from being changed, that is, that the variable points to another different object and potentially is a new value.

I made examples and commented on the codes that would not work in order 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);
}

See running on ideone . And No Coding Ground . Also put it on GitHub for future reference .

It's interesting to understand What's the difference between statement and definition? .

    
15.03.2017 / 12:25