char * const VS const char *

Started by
5 comments, last by wildem 18 years, 2 months ago
Hello! I'm wondering what's the difference between char * const and const char *, but I have a pretty good idea : char * const : means you cannot write to what's pointed by the variable const char * : means you cannot change the pointer's adress 1- I'm I right? 2- If i'm only going to read from a char *, should I write : void foo(const char * const); thanks!
Advertisement
1) Other way around. const char * means that you can't modify the char pointed to by the pointer. char * const means you can't modify the pointer.

2) No point. Just make it a const char *.
1 - You have it backwards.
2 - Not really, a const char * is fine.
.
Other way around, if memory serves correctly. const char* is a pointer to a constant char, whereas a * const is a constant pointer.

As for the second one, since const char* is defined at declaration, I don't see much reason to make it a constant pointer - you can't change it anyways.
Hey triple thanks!

And you managed to give me the same answer so I can't be mistaking!
To elaborate, it doesn't really ever make sense to pass function arguments by const value, because a change to the value wouldn't be seen by the caller *anyway*. But it *does* make sense to declare that a function argument is a pointer to const data, because otherwise you could change data through the pointer that would then be seen by the caller.

But then, you should be using references where possible and pointers where necessary, and using std::string rather than char* to represent text (assuming no special circumstances) - yes? :)
"If i'm only going to read from a char *, should I write :
void foo(const char * const);"

just use:

void foo(const char *string);

This will do for reading from the string, without changing it...

[]wildem[]

This topic is closed to new replies.

Advertisement