Home > Net >  What is a call to `char()` as a function in C ?
What is a call to `char()` as a function in C ?

Time:05-25

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: enter image description here

Adjacently related

  1. What motivated me to study the std::string::resize() method was trying to learn how to pre-allocate a std::string for use in C function calls as a char* buffer. This is possible by first pre-allocating the std::string by calling the my_string.resize() function on it. Then, you can safely write into &my_string[0] as a standard char* up to index my_string.size() - 1. See also:
    1. Directly write into char* buffer of std::string
    2. Is there a way to get std:string's buffer

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.

  • Related