Reputation: 1955
I was faced with this question for a C++ exam and as much as I think I know the answer, the question confused me enough that I rather have a "Second opinion" per say... haha.
a) The literal
"Hello, World!"
is a C-Style string. What is its type?b) Given that the type of C-style string and the type
std::string
are different, how is it possible that the linestd::string hello("Hello,World!");
compiles without errors/warnings (assuming the<string>
header has been included)?
From my understanding the C-Style string is of type (a) array of chars while std::string
is of type string... and (b) the reason it compiles is that in C++ the whole casting to chars and all that is done "under the hood" by the type string rather than "in the code".
Am I correct?
Thanks!
Upvotes: 1
Views: 406
Reputation: 145829
In C++, the type of "Hello, World!"
is an array of 14 const char
and in C the type is an array of 14 char
. The trailing null character of the string is a part of the array.
Upvotes: 2
Reputation: 279255
What you say is probably close enough to be called "true", although you're missing some detail. The type of the literal "Hello, World!"
in C++ is const char[14]
. As you say that's an array of chars, but the size is part of the type.
std::string
has a constructor that takes const char*
, and there's an implicit conversion from const char[14]
to const char*
. Those two together handle (b).
There's no "casting to chars" involved, though.
Upvotes: 6