The const keyword (part 2)

Posted by Strainu on May 29, 2007
C, C++

In part 1 we introduced the const keyword. Today we’ll talk about constant pointers.

Let’s say you want to define a constant pointer. Which of the following declarations will you use?

const int* v1;
int* const v2;
const int * const v3;

The answer is: the second or the third. The first declaration defines a pointer to a constant integer and the third one defines a constant pointer to a constant integer.

Another interesting case is when defining a constant char array (credits go to Ulrich Drepper, link via RazvanD):

int main(void)
const char s[] = "hello";
strcpy (s, "bye");
puts (s);
return 0;

Although this code will give a warning (passing `const char *’ as argument 1 of `strcpy(char *, const char *)’ discards qualifiers is the exact message on Dev-C++), it will run, because s is allocated in the heap, so it is treated much like a pointer. You can force the value to be constant by adding the static keyword, wich will force the compiler to allocate s in read-only memory:

static const char s[] = "hello";
Share and Enjoy:
  • Facebook
  • Twitter
  • LinkedIn
  • Reddit
  • Add to favorites

Tags: ,

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.