Assume a function with one parameter of const char*
type. When I use a string when calling that function, nothing goes wrong! I would expect that you could only input characters included in the ASCII, for example c
or dec 68
, but it seem otherwise. Take a look at the code below...
void InitFunction(const char* initString)
{
std::cout << initString;
}
int main()
{
InitFunction("Hello!");
}
When you run the code, no problem, warnings, or errors appear. I did some more testing on this as you can see from the following...
void InitFunction(char initString)
{
std::cout << initString;
}
int main()
{
InitFunction("Hello!"); // compiler error on this line
}
This compiles with an error since Hello!
cannot be converted into char
. I tried another test, but instead used const char
as the function parameter type. The code still compiles with an error. But when I add *
to the function parameter type, then everything compiles fine! It appears to me that the const
is also necessary.
To my understanding of pointers, the function is asking for a pointer, and the pointer is identified as being a character. But this raises three problems for me.
First,
Hello!
is not in the form of a pointer. I would expect at least to have to use the reference operator (&
).Second,
Hello!
is not achar
type.And third, why do we need to include the
const
?
Am I missing something here? Do pointers and characters work in ways that I don't know?