Navigation



6.10 — Pointers and const

Just like normal variables, pointers can be declared constant. There are two different ways that pointers and const can be intermixed, and they are very easy to mix up.

To declare a const pointer, use the const keyword between the asterisk and the pointer name:

int nValue = 5;
int *const pnPtr = &nValue;

Just like a normal const variable, a const pointer must be initialized to a value upon declaration, and its value can not be changed. This means a const pointer will always point to the same value. In the above case, pnPtr will always point to the address of nValue. However, because the value being pointed to is still non-const, it is possible to change the value being pointed to via dereferencing the pointer:

*pnPtr = 6; // allowed, since pnPtr points to a non-const int

It is also possible to declare a pointer to a constant variable by using the const before the data type.

int nValue = 5;
const int *pnPtr = &nValue;

Note that the pointer to a constant variable does not actually have to point to a constant variable! Instead, think of it this way: a pointer to a constant variable treats the variable as constant when it is accessed through the pointer.

Thus, the following is okay:

nValue = 6; // nValue is non-const

But the following is not:

*pnPtr = 6; // pnPtr treats its value as const

Because a pointer to a const value is a non-const pointer, the pointer can be redirected to point at other values:

int nValue = 5;
int nValue2 = 6;

const int *pnPtr = &nValue;
pnPtr = &nValue2; // okay

Confused? To summarize:

  • A non-const pointer can be redirected to point to other addresses.
  • A const pointer always points to the same address, and this address can not be changed.
  • A pointer to a non-const value can change the value it is pointing to.
  • A pointer to a const value treats the value as const (even if it is not), and thus can not change the value it is pointing to.

Finally, it is possible to declare a const pointer to a const value:

const int nValue;
const int *const pnPtr = &nValue;

A const pointer to a const value can not be redirected to point to another address, nor can the value it is pointing to be changed.

Const pointers are primarily used for passing variables to functions. We will discuss this further in the section on functions.

6.11 — References
Index
6.9 — Dynamic memory allocation with new and delete

23 comments to 6.10 — Pointers and const

  • Anand

    Sir,
    I am working on my Mtec project in that i am working with STEP file, it contain a large dada, for example 30000 lines, i want to extract the dada which i required i have done a program in C++ , such a way that it checks all the lines and extracts the data what i required but it takes more than half hour, can i use dynamic memory allocation or other concept so the time required would would be 2 to 3 min only. Thanks in advance. If possible please reply.
    Thank You.

  • [...] 2007 Prev/Next Posts « 6.8 — Pointers, arrays, and pointer arithmetic | Home | 6.10 — Pointers and const » Friday, July 13th, 2007 at 5:24 [...]

  • som shekhar
    int nValue = 10;
    const int *ptr = &nValue;
    *ptr = 12;
    

    if i do like this then i m getting compiler error saying l-value specifies const object

  • Pawan

    How i can input all keyboard keys in cpp. Like del,arrow,F1 etc.

  • JLight

    Hi.

    Firstly i am getting a huge amount out of this course, the way it is laid out means i am ready for each new concept as i find it, and i’m learning alot about programming, not just C++.

    Have i got it wrong or in your last example about should you not assign the constant int nValue in line one?

    Cheers V much for the time this must have taken, fantastic and fun too!

    I would love more quizzes to get practicle practice though. I’ve been setting myself tasks, but its difficult to think of tasks that really test you cos they’re usually based on what i can do, not what i should be able to do…

  • Learner

    When you talk about const pointer to const value:

    const int nValue;
    const int *const pnPtr = &nValue;

    We must give some initial value to nValue while declaring it, since it is a constant variable. Right?

  • Dr. HaXX

    Could you please tell me what you mean by stuff like this:

    ]czo3OlwicG5QdHIrMVwiO3tbJiomXX0=[
  • Is there any reason I shouldn’t use a pointer to a const value in defining array sizes as opposed to using dynamic memory allocation? The following code seems much less dangerous and prone to memory leaks than allocating the memory dynamically:


    int nArraySize = 5;
    const int *pnSizePointer = &nArraySize;
    int anArray[*pnSizePointer];

    Am I right?

    • broadwayLamb

      I am curious about this too. This is a really interesting bit of code. I tested a few things just to see what could be done with it, and I did find a potential danger in declaring a variable this way.

      If you declare an array’s size by dereferencing a pointer to a number X, and then later you change the size of X, then the program will believe that the size of the array has changed.

      Consider this code:

      int main()
      {
      /* We create a variable and pointer and use them in the suggested manner
      to initialize an array of ten items. We then output the size of the array */
      int arraySize = 0;
      const int *sizePtr = &arraySize;

      arraySize = 10;
      int oneArray[*sizePtr];
      cout << "First array uses " << sizeof(oneArray) << " bytes" << endl;

      /* Now we reset the arraySize variable again to create a new array of 5 items.
      We then print out the size of this array */

      arraySize = 5;
      int twoArray[*sizePtr];
      cout << "Second array uses " << sizeof(twoArray) << " bytes" << endl;

      /* Now has anything changed with the first array? */

      cout << "After changing the arraySize variable, oneArray is now " << sizeof(oneArray) << " bytes" << endl;

      return(0);
      }

      Here is the output:

      First array uses 40 bytes
      Second array uses 20 bytes
      After changing the arraySize variable, oneArray is now 20 bytes

      We can see the program now believes that the first array is only 5 items long, but as programmers we may be expecting that first array still be 10 items long.

      Imagine the situation in reverse… we declare an array with size based on a variable, then later we raise the value of that variable dramatically. Now the array thinks it is larger that it was when it was allocated, but if you work with that extra space you could be modifying memory that belongs to other variables or code.

  • fmunshi

    What if I have the following:

    int x = 5;
    const int *const ptrToX = &x

    From what I understand, this is a constant pointer to a constant integer.
    The pointer cannot be made to point at another address.
    The pointer cannot change the value of the integer at the address it points to.
    BUT, I can change the value of x like this:

    x = 6;

    because the integer x is itself not a const integer but the pointer is treating the variable as a const when it is accessed through the pointer.

    Thanks,
    Fardan

  • sw1983

    Can you please explain in more detail why this snippet of code is ok? Earlier int he tutorial you said a const pointer always points to the same address. That code looks to me like it is assigning a different address to a const pointer. Or maybe I have misunderstood?

    Great tutorials by the way.

    “Because a pointer to a const value is a non-const pointer, the pointer can be redirected to point at other values:”

    1 int nValue = 5;

    2 int nValue2 = 6;

    3

    4 const int *pnPtr = &nValue;

    5 pnPtr = &nValue2; // okay

  • sw1983

    Ignore that last question I’ve read again and understand now:

    int const *pnPtr is a variable pointer to a constant value.
    a constant pointer would be int *const pnPtr.

  • hypehuman

    Dear Alex,

    This tutorial is awesome! As I am going through it, I am building a program that will play Minesweeper by itself. It works right now, but I am modifying it daily to apply the good programming practices I am learning here.

    Anyway, I see you typed: “a const pointer will always point to the same value“.
    Did you mean: “a const pointer will always point to the same location“?

    Maybe I’m just not understanding it.

  • Sultan

    Hi there,

    I don’t understand what the benefit is when we declare a pointer as constant.

    Any help?

  • [...] Variables Dynamic Arrays 2-D Dynamic Arrays – How To Declare Bubble Sort While Loops For Loops Constant Variables Functions Switch Statements Toupper Strcpy [...]

  • MidnightRider

    So far i uderstand the pointers but i need to practice,any help ?

  • alwaysAstudent

    Please correct me if I am wrong. I think that the relation between pointers and constant can be best understood when seen from pointers’ point of view.

    CONSTANT POINTER : is a pointer which is constant; meaning it holds a constant value (address which it points to). that is, it constantly points to the address of a variable (assigned during declaration). the variable may not be a constant. thus the constant pointer points to one unique address and can manipulate the variable that has that address. hence,

    int nValue = 5;
    int *const pnPtr = &nValue;
    *pnPtr = 6; // it is possible !!
    nValue = 7; // this is also possible !! inadvertently skipped in this tutorial i guess

    POINTER TO A CONSTANT VARIABLE :

    the variable may not be a constant but still, when declared this way, the pointer treats the variable as a constant.

    int nValue = 5;
    const int *pnPtrt = &nValue; // POINTER TO A CONSTANT VARIABLE
    nValue = 6; // this can be done as the variable need not be constant

    however, *pnPtr = 7; will cause program to crash because the pointer pnPtr treats nValue as a constant.

    CONSTANT POINTER TO A CONSTANT VARIABLE :

    here, both the pointer as well as the variable, are constant.

    const int nValue = 5;
    const int *const pnPtr = &nValue;

    nValue = 6; // not possible because nValue is a constant
    *pnPtr = 6; // not possible because pnPtr is pointer to a constant ( and not because pnPtr is a constant pointer !)

  • sumit agrawal

    #include

    int main()
    {
    using namespace std;
    int nvalue=10;
    int nvalue2=5;
    const int *ptr=&nvalue;
    nvalue=20;
    cout << *ptr << endl;
    cout << nvalue << endl;
    return 0;
    }

    output:
    20
    20

    why so..?? the value of nvalue should be constant to 10 if we access it through *ptr but here its changing to 20 even if we are accessing it through *ptr…may b m lacking in understanding the concept…still can some1 plz clarify me dis…

You must be logged in to post a comment.