Constant Pointers and Pointers to Constants

In the CodeGuru newsletter, I brought up the topic of constant pointers and pointers to constants. While this is a beginning level topic, it is one that some advanced-level people goof up in their code.

Pointer contants and contant pointers are also something that many people simply don't use. If you have a value in your program and it should not change, or if you have a pointer and you don't want it to be pointed to a different value, you should make it a constant with the const keyword.

There are generally two places that the const keyword can be used when declaring a pointer. Consider the following declaration:

char A_char = 'A';
char * myPtr = &A_char;

This is a simple declaration of the variable myPtr. myPtr is a pointer to a character variable and in this case points to the character 'A'.

Don't be confused about the fact that a character pointer is being used to point to a single character—this is perfectly legal! Not every character pointer has to point to a string.

Now consider the following three declarations assuming that char_A has been defined as a type char variable.:

const char * myPtr = &char_A;
char * const myPtr = &char_A;
const char * const myPtr = &char_A;

What is the difference between each of the valid ones? Do you know?

They are all three valid and correct declarations. Each assigns the addres of char_A to a character pointer. The difference is in what is constant.

The first declaration:

const char * myPtr

declares a pointer to a constant character. You cannot use this pointer to change the value being pointed to:

char char_A = 'A';
const char * myPtr = &char_A;
*myPtr = 'J';    // error - can't change value of *myPtr

The second declaration,

char * const myPtr

declares a constant pointer to a character. The location stored in the pointer cannot change. You cannot change where this pointer points:

char char_A = 'A';
char char_B = 'B';

char * const myPtr = &char_A;
myPtr = &char_B;    // error - can't change address of myPtr

The third declares a pointer to a character where both the pointer value and the value being pointed at will not change.

Pretty simple, but as with many things related to pointers, a number of people seem to have trouble.

# # #

About the Author

Bradley Jones

Bradley Jones, in addition to managing CodeGuru, Brad! oversees the Developer.com Newtwork of sites including Codeguru, Developer.com, DevX, VBForums, and over a dozen more with a focus on software development and database technologies. His experience includes development in C, C++, VB, some Java, C#, ASP, COBOL, and more as well as having been a developer, consultant, analyst, lead, and much more. His recent books include Teach Yourself the C# Language in 21 Days, Web 2.0 Heroes, and Windows Live Essentials and Services.
Google+ Profile | Linked-In Profile | Facebook Page

IT Offers

Comments

  • code optimization using const

    Posted by cscos on 10/26/2011 11:08am

    Hello,
    
    I want to use this to optimize my program.
    Let's say I have a structure like this that I use for many stuff.
    
    typedef struct
    {
      unsigned char workspace[1024*1024];
      unsigned int flags;
    } my_stuff_t;
    
    I have this declared in my_stuff.c :
    
    my_stuff_t my_stuff;
    
    and in my_stuff.h:
    
    extern my_stuff_t my_stuff;
    
    What I want to do is to have another data type points into this structure, in another file.
    
    For example, in my_data.c:
    
    #include "mystuff.h"
    
    typedef struct
    {
      ...
    } custom_t;
    
    custom_t* const data =(custom_t *) (my_stuff.workspace[2*1024]);
    
    and in my_data.h:
    
    extern custom_t* const data;
    
    What I want is that the compiler directly compute the value of data when dealing with it in external code. But when I generate the assembly code, it seems that gcc is still using a load instruction to read "data" address  from the pointer in memory. Off course, any code in my_data.c that use "data" is fine (assembly code is as expected, with direct use of my_stuff address), I'm talking about external object files that include my_data.h
    
    So, is that possible to force the compiler to assume the address is contant and thus not reading it from the pointer address but use a precomputed symbol (later resolved by linker) ?

    Reply
  • tell me

    Posted by imagin3012 on 07/10/2011 06:09pm

    What is the diff between
    
    int const *ptr
    and
    const int *ptr
    ??

    • same

      Posted by ahp on 03/30/2012 11:12am

      both are same.

      Reply
    Reply
  • Excellent

    Posted by rasmiranjanbabu on 04/26/2011 06:51am

    Excellent Job Boss............. Very Informative...
    Keep it Up

    Reply
  • what about c style pointer to string.

    Posted by atif_ilm on 06/16/2005 12:46am

    what if i have something like this char *str="Hello World"; is this imply the str is the pointer to constant data. as when i do some strcpy kind of operation on str , it will assert. so can we say that char *str="Hello World" equal to const char *str="Hello World" if yes , why is it implicit.

    • re: what about c style pointer to string

      Posted by Smasher/Devourer on 06/28/2005 09:47pm

      Please see this Item from Guru of the Week for a bit of an explanation: http://www.gotw.ca/gotw/009.htm Basically, a C++ program has an area of memory called const data, which stores data whose values are known at compile time, such as string literals. Because a declaration such as the one in your comment creates a pointer aimed directly at this region of memory, rather than allocating new (modifiable) memory and copying the string literal into it, the results of attempting to write to it are undefined.

      Reply
    Reply
  • Examples switched

    Posted by hiccup on 04/16/2004 12:35pm

    The declarations of myPtr are switched in the two examples: The statements are switched in the 1st and second examples: const char * myPtr declares a pointer to a constant character. You cannot use this pointer to change the value being pointed to: char char_A = 'A'; --> char * const myPtr = &char_A; // should be const char* myPtr ... *myPtr = 'J'; // error - can't change value of *myPtr

    • Doh!

      Posted by Brad Jones on 04/16/2004 05:32pm

      That is what I get for letting someone get me to post it before I proofed it. It should be a bit better now (assuming the cache on the site has refreshed the article ).

      Reply
    Reply
Leave a Comment
  • Your email address will not be published. All fields are required.

Whitepapers and More

Most Popular Programming Stories

More for Developers

Latest Developer Headlines

RSS Feeds