I've never seen this call to char()
as a function before. Where is this described and what does it mean? This usage is part of the example on this cppreference.com community wiki page:
Adjacently related
- What motivated me to study the
std::string::resize()
method was trying to learn how to pre-allocate astd::string
for use in C function calls as achar*
buffer. This is possible by first pre-allocating thestd::string
by calling themy_string.resize()
function on it. Then, you can safely write into&my_string[0]
as a standardchar*
up to indexmy_string.size() - 1
. See also:
CodePudding user response:
It returns 0
with the specified type, same as char(0)
. It's called value initialization.
The syntax mimics that of calling a default constructor for a class.
CodePudding user response:
It's the constructor† for char
; with no arguments it constructs '\0'
. Rarely used since primitives offer other ways to initialize them, but you initialize them with ()
just like you would a user-defined class, which ensures they get initialized to something; char foo;
has undefined value, while char foo = char();
or char foo{};
is definitely '\0'
.
†As HolyBlackCat notes, it's not technically a constructor, because it's not a class, but it behaves like one for most purposes.