const char*
and char *
are actually not the same. The later allow for modifying the pointed char
, while the first one will prevent that.
Also note that if those were class methods, void display()
and void display() const
would also be valid overloads. The later would imply that the method must not change the object's state.
Consider this code:
void display(char *s)
{
std::cout << "Display" << std::endl;
}
void display(const char *s)
{
std::cout << "Display with const" << std::endl;
}
int main()
{
char *str = strdup("boap");
const char *str2 = "toto";
/* It is a string literral "bound" as a char *.
Compiler will issue warning, but it still compiles.
Avoid to do that, it's just an exemple */
char *not_safe = "not_safe";
display("llama");
display(str2);
display(str);
display(not_safe);
}
This will print Display with const
twice, and then twice Display
. See there.
Now, let's see why:
"llama"
is a string literal, and then is resolved as aconst char *
.str2
is a pointer to a string literal. Since its type isconst char*
, this also revolves to theconst
overload.not_safe
is also a pointer to a string literal. However, its type ischar *
: this is not correct. The memory it points to is read-only, and trying to modifies it will result in a crash. However, the type of the variable is stillchar *
, so this resolve to the non-const
overload.str
is achar *
pointer, and the string it points to is not read-only. Modifying its content is valid, and since its type ischar *
, it will resolve to the non-const overload.