How does the const keyword affect a pointer pointing to a const variable?

If you consider this:

int *var1;
const int *var2 = var1;

      

Why

*var1 = x; 

      

compile and

*var2 = x; 

      

not?

+3


source to share


2 answers


In your case

 *var2 = x;

      

fails to compile with error message (approximate),

error: assigning read-only space *var2

 *var2 = 10;
       ^

      

because you pointed out that value matters const

.


To clarify, you can read the instruction like



  const int *var2;

      

as, declare var2

as a pointer to const int

. Thus, the value it points var2

to is constant and cannot be changed.

If you want the pointer itself to be const qualified, you need to write something like

 int * const var2;

      

which basically declares var2

as a const

pointer to int

.

So, in the future, any attempt to assign var2

will result in an error, but access to *var2

will work fine, since the value that the pointer points to is no longer a const construct.

+3


source


Using const int * in this context helped me understand:

int 
sum( const int *x, const int *y )
{
    return *x + *y;
}

int
main(void)
{ 
    int x = 10;
    int y = 10;
    int sum;

    sum = sum &x, *y );
}

      



Putting const int * qualifier in the functional arguments means that the value of x and y are immutable (not mutable) inside the function.

But other than this usage, I find const int * very confusing.

0


source







All Articles