There are many times that I get compile errors when I use char*
instead of const char*
. So, I am not sure the actual difference, the syntax and the compile mechanism.
Simple: "char *name" name is a pointer to char, i.e. both can be change here. "const char *name" name is a pointer to const char i.e. pointer can change but not char.
C. NOTE: There is no difference between const char *p and char const *p as both are pointer to a const char and position of '*'(asterik) is also same.
You absolutely can assign const char* to std::string , it will get copied though. The other way around requires a call to std::string::c_str() .
If you're after the difference between the two, just think of them as:
const char *
means "pointer to an unmodifiable character." It's usually used for strings of characters that shouldn't be modified.
Say you're writing this function:
int checkForMatch(const char * pstr)
You've promised (through the function signature) that you will not change the thing pointed to by pstr
. Now say part of checking for a match would involve ignore the case of letters, and you tried to do it by converting the string to upper case before doing your other checks:
strupr(pstr);
You'll get an error saying you can't do that, because strupr
is declared as:
char * strupr(char* str);
...and that means it wants to be able to write to the string. You can't write to the characters in a const char *
(that's what the const
is for).
In general, you can pass a char *
into something that expects a const char *
without an explicit cast because that's a safe thing to do (give something modifiable to something that doesn't intend to modify it), but you can't pass a const char *
into something expecting a char *
(without an explicit cast) because that's not a safe thing to do (passing something that isn't meant to be modified into something that may modify it).
Of course, this is C, and you can do just about anything in C, including explicitly casting a const char *
to a char *
— but that would be a really, really bad idea because there is (presumably) some reason that the thing being pointed to by the pointer is const
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With