views:

93

answers:

1

Wikipedia says "const" is "...a special kind of variable whose value cannot typically be altered by the program during its execution..."

If that is the case, why does this:

const char *words[4] = { "aardvark", "abacus", 
                             "allude", "zygote" };

    *words = "first";
    words[1] = "second";

    int wordCount = 4;

    int i;
    for (i = 0; i < wordCount; i++) {
        NSLog (@"%s is %d characters long",
               words[i], strlen(words[i]));
    }

have an output of: "first" "second" "allude" "zygote" (obviously with the length etc.)

I thought the whole point of "const" was to prevent the variable of being modified??

+8  A: 

The const only applies to the char, i.e. the content of the strings themselves, but not to the array. If you want the content of the array to be constant as well, you need to add const to every level:

char const* const words[4] = { "aardvark", "abacus", "allude", "zygote" };
//   ^      ^
//   |      This makes words[x] = "abc"; fails.
//   |
//   This makes words[x][y] = 'a'; fails
KennyTM
I wish that clarified things...
Rob