const int pointer error

I am learning about constant pointers and I was trying this

1
2
3
4
5
6
7
8
9
10
  
    #include<iostream>
    using namespace std ;
    int main(){
    	int a = 10 ; 
    	const int *cp  = &a ; 		// my constant pointer variable
    	cout<<"\nAddress stored in cp = "<<cp ;
    	++cp;
    	cout<<"\nAddress stored in cp = "<<cp   ;
    }


It incremented the address which was stored in `cp`
But according to what I have understood until now, shouldn't `++cp` give an error as it is a constant pointer that always points to the same address and this address cannot be modified.

But when I replaced

[/code]const int *cp = &a ;[/code] with [/code]int *const cp = &a;[/code]

Then it gives me an error.

Forgive my ignorance but, aren't they suppose to mean the same thing ?
aren't they suppose to mean the same thing ?
No
const int * or int const * means pointer to constant int: you can change pointer but not the value it points to
int* const means const pointer: you cannot change pointer, but can change value it points to.

Yopu can freely mix those: const int* const or int const * const means pointer you cannot change in any way.

By the way ++cp; in your program is illegal. Pointer arithmetics is only valid for pointers which points to the array, not the individual elements. Although it probably works as you expect, it is UB and in any more complex program this can lead to problems.
Last edited on
const int* is non-const pointer to a const int.

int* const is a const pointer to a non-const int.

I haven't slept all night but I think it's instead of:

int *const cp = &a;

Try:

int* const cp = &a;


It's the data you want to make a pointer, not the const. I think.
Spaces doesn't matter here.
1
2
3
4
5
// All the same:
int*const
int* const
int *const
int * const
I could of sworn g++ threw an error on the third, perhaps it's time to take a break.
Topic archived. No new replies allowed.