Why const int* is not constant?

Take thoose exemples:

1
2
3
4
5
6
7
8
{
    const int *a;
    int ab = 11;
    int bc = 12;
    a = &ab;
    a = &bc;
    return 0;
}

if it is a const value why i can change it's value?
with a const int i can't because like the name says it's a constant value, but why this does not apply to pointers?
it's because pointer is not constant, only value is constant in your case..

consider this:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
	int ab = 11;

	// SCENARIO 1
	const int* a; // this is a non-constant pointer pointing to constant value
	*a = 4; // error value is constant
	a = &ab; // OK, pointer is not constant

	// SCENARIO 2
	int* const b = &ab; // this is a constant poiner pointing to non-constant value
	*b = 4; // Ok: value is not constant
	b = &a; // error: pointer is constant

	// SCENARIO 3
	const int* const c = &ab; // this is a constant poiner pointing to constant value
	c = &b; // error: pointer is constant
	*c = 4; // error: value is constant 


explanation:
if you put const in front of * then value is constant
if you put const after the * then pointer is constant
if you put const both in front and after * both pointer and value are constant
if you put no const at all, neither value nor pointer are constant.

edit:
the value does not need to be constant, what const in front of * says is that value can't be modified. be it const or not.

if in the above example ab is declared as const int ab = 11 then declaring int* const pointer would not work.
Last edited on
Topic archived. No new replies allowed.