How does the const keyword affect a pointer pointing to a const variable?
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.
source to share
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.
source to share