Strainu onLine
Blogul unui automatist
29th
MAY
The const keyword (part 2)
Posted by Strainu | Filed under 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?
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):
{
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:
Leave a Reply
Post Meta
-
May 29, 2007 -
C, C++ -
No Comments
-
Comments Feed -
Facebook
-
Tweet This




