The const keyword (part 2)

Posted by on mai 29, 2007
Fără categorie

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";

Lasă un răspuns

Adresa ta de email nu va fi publicată. Câmpurile obligatorii sunt marcate cu *

Acest site folosește Akismet pentru a reduce spamul. Află cum sunt procesate datele comentariilor tale.