I initialize a char[]
array with a "hello"
string:
char str[] = "hello";
func(str);
Now, the char[]
array is passed to a function, taking a const char*
pointer parameter:
void func(const char* str)
{
puts(str);
}
Output:
hello
Why don't I need to typecast the char[]
array to a const char*
pointer?
Why I don't need to type cast the char type pointer to const char type pointer?
Because of the implicit qualification conversion. In particular, a pointer to a nonconst type can be converted to a pointer to the corresponding const
type.
This can be seen from implicit conversion:
A prvalue of type pointer to cv-qualified type
T
can be converted to a prvalue pointer to a more cv-qualified same typeT
(in other words, constness and volatility can be added)."More" cv-qualified means that
a pointer to unqualified type can be converted to a pointer to
const
;...
(emphasis mine)
For example,
int i = 0;
const int *p = &i; // conversion to const happens here