const Correctness: Difference between Foo* const ptr, const Foo* ptr, const Foo* const ptr
Posted by tekpool on January 10, 2007
- Foo* const ptr: ptr is a const pointer to a Foo Object. The Foo object can be changed using the pointer ptr, but you can’t change the pointer ptr itself.
- const Foo* ptr: ptr points to a Foo object that is const. The Foo object can’t be changed via ptr.
- const Foo* const ptr: ptr is a const pointer to a const Foo object. Neiher can the pointer ptr be changed, nor can you change the Foo object using ptr.
Reading the declaration right to left is a easy way to remember what they mean.
Sharad Upadhyay said
Hi Andreas,
Can you please post your comment of O(1) space merge of two sorted arrays? It would be good to know how it works. It is needed for O(NlogN) time and O(1) space merge sort algorithm. Most of the books talk about extra O(N) space solution, please let me know which book explain O(1) space merge sort.
Marinkina said
Пора переименовать блог, присвоив название связанное с доменами
может хватит про них?
Me said
Thanks for the post. Check
Me said
http://www.technical-interview.com
Manas said
will you tel me code of c++ for double link list .i m fresher thats why unable to solve technical aptitude .
Lincoln Ramsay said
The const keyword applies to the item to its immediate left.
However, most people use it as the first token in a statement because of a backwards-compatibility hack in the language. When const is the first token it applies to the item to its immediate right.
Here’s some examples:
const Foo * ptr; // variable pointer to constant Foo object (special case)
Foo const * ptr; // variable pointer to constant Foo object
Foo * const ptr; // constant pointer to variable Foo object
Foo const * const ptr; // constant pointer to constant Foo object
And now you know why const methods have the const at the end…
void Foo::method() const; // method that can be run on constant instances of the Foo object
Note that using a constant pointer to constant data prevents the pointer from having to be initialized when the program starts.
char const * const mystring = “blah”; // both the pointer and data are set at compile time
const char * mystring = “blah”; // allocate and initialize the variable mystring pointer at run-time
7 Reasons Why Competition is Good said
7 Reasons Why Competition is Good…
[...]const Correctness: Difference between Foo* const ptr, const Foo* ptr, const Foo* const ptr « Technical Interview Questions[...]…
keyword said
keyword…
[...]const Correctness: Difference between Foo* const ptr, const Foo* ptr, const Foo* const ptr « Technical Interview Questions[...]…