this
const char* tok;
creates a pointer on the stack. It has an undefined value, it points nowhere
this
for (tok = strtok(line, ";");
then makes it point to somewhere in line (depends on contents)
your comments
My understanding of const char * declarations is that it defines a mutable pointer to an immutable array of characters. This array is assigned in the data section at compile time.
First sentence, almost, it creates a pointer that might point to an immutable array of chars. Like this
const char * msg = "hello world";
But is can also point nowhere
const char * msg = NULL;
Or to a mutable array of characters
char msg[] = "HelloWorld"; // mutable const char *msgconst = msg;
the second sentence
This array is assigned in the data section at compile time
Yes, if this is a literal. Ie like this example again
const char*msg = "Hello World";
but the msgconst assignment is not like that, the characters are on the stack
Hope this helps
EDIT
The pointer points where it is told to do, making it const or not has zero effect on where the data is. The data is where it is.(!). You need to think about where the data is created, nothing to do with the pointer, the pointer can point at a literal, stack data, static data (mutable in data segment), heap.
Why use const
if the string is immutable then the pointer must be const. C allows you to assign a literal to a non const pointer for historical reasons, c++ does not
You want to make it clear that this string should not be changed. In your code case you really should not mess with the string strtok is processing. Although it returns char* , this is good practice
functions like strlen that do not change the string passed to them declare their arguments as const char*, its part of their contract: we dont change the string
But having the word const does not change anything about storage, and does not save any space anywhere
const char T*declares a pointer to an object (which might be the first object in an array of such objects) which you promise you won't try to modify. The compiler will probably help you keep that promise by producing warning or error messages if it detects that you are trying to modify an object through that pointer, but it can't actually know in all cases. However, it is allowed to optimise, assuming that you will play by the rules. If you read a value from that pointer twice, the compiler might eliminate the second read and assume that the first value is still valid.const. The compiler is likely to produce useful error messages (since modifying a value you didn't plan to modify is almost certainly an error). It might even warn you about passing the pointer as an argument to a function which might try to modify the value pointed to. So it can help. But it doesn't guarantee that the memory being pointed at is read-only.