Piddy
Piddy

Reputation: 59

How does the const keyword affect a pointer that is pointing towards a const variable?

If you consider this:

int *var1;
const int *var2 = var1;

Why does

*var1 = x; 

compile and

*var2 = x; 

does not?

Upvotes: 3

Views: 66

Answers (2)

Nguai al
Nguai al

Reputation: 958

The usage of const int * in this context helped me to 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 );
}

By putting const int * qualifier at functional arguements, this is saying that the value x and y are immutable(not modifiable) inside the function.

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

Upvotes: 0

Sourav Ghosh
Sourav Ghosh

Reputation: 134326

In your case

 *var2 = x;

fails to compile with error message (approx),

error: assignment of read-only location *var2

 *var2 = 10;
       ^

because you have marked the value to be of const qualified.


To elaborate, you can read a statement like

  const int *var2;

as, declare var2 as pointer to const int. So the value pointed to by var2 is constant and cannot be changed.

In case you want the pointer itself to be const-qualified, you need to write something like

 int * const var2;

which basically is declaring var2 as const pointer to int.

So, later any attempt to assign to var2 will produce the error, but accessing *var2 will work fine, as the value pointed to by the pointer is not const-qualified anymore.

Upvotes: 3

Related Questions