Sign in to follow this  

char * const VS const char *

This topic is 4337 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

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!

Share this post


Link to post
Share on other sites
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 *.

Share this post


Link to post
Share on other sites
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.

Share this post


Link to post
Share on other sites
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? :)

Share this post


Link to post
Share on other sites
"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[]

Share this post


Link to post
Share on other sites

This topic is 4337 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this