Follow Techotopia on Twitter

On-line Guides
All Guides
eBook Store
iOS / Android
Linux for Beginners
Office Productivity
Linux Installation
Linux Security
Linux Utilities
Linux Virtualization
Linux Kernel
System/Network Admin
Programming
Scripting Languages
Development Tools
Web Development
GUI Toolkits/Desktop
Databases
Mail Systems
openSolaris
Eclipse Documentation
Techotopia.com
Virtuatopia.com
Answertopia.com

How To Guides
Virtualization
General System Admin
Linux Security
Linux Filesystems
Web Servers
Graphics & Desktop
PC Hardware
Windows
Problem Solutions
Privacy Policy

  




 

 

Thinking in C++
Prev Contents / Index Next

const pointer

To make the pointer itself a const, you must place the const specifier to the right of the *, like this:

int d = 1;
int* const w = &d;

Now it reads: “w is a pointer, which is const, that points to an int.” Because the pointer itself is now the const, the compiler requires that it be given an initial value that will be unchanged for the life of that pointer. It’s OK, however, to change what that value points to by saying

*w = 2;

You can also make a const pointer to a const object using either of two legal forms:

int d = 1;
const int* const x = &d;  // (1)
int const* const x2 = &d; // (2)

Now neither the pointer nor the object can be changed.

Some people argue that the second form is more consistent because the const is always placed to the right of what it modifies. You’ll have to decide which is clearer for your particular coding style.

Here are the above lines in a compileable file:

//: C08:ConstPointers.cpp
const int* u;
int const* v;
int d = 1;
int* const w = &d;
const int* const x = &d;  // (1)
int const* const x2 = &d; // (2)
int main() {} ///:~
Thinking in C++
Prev Contents / Index Next

 
 
   Reproduced courtesy of Bruce Eckel, MindView, Inc. Design by Interspire