0

I tried to find documentation on this but there doesn't seem to be any definite answers to this. I tried in an example program, and it seems to \0 but is this reliable behavior? What does char() initialize to and is this in the C++ standard.

int main()
{
  std::cout<<char()<<std::endl;

  return 0; 
}
TWhite
  • 45
  • 6
  • 2
    `char()` doesn't print anything. It creates a value-initialized (e.g. zero-initialized in this case) `char` temporary. What you do with it thereafter is up to you. – WhozCraig Mar 20 '22 at 02:02
  • Please edit your question to show the code you want to know the behaviour of. _"what does char() print out"_ is kinda loosey-goosey language. Specific code is best in this case to define what you mean. – Wyck Mar 20 '22 at 02:12
  • I've added a simple program. @WhozCraig do you mean the numerical `0`? When I run the program I provided it is a blank. – TWhite Mar 20 '22 at 04:12
  • 1
    That's the overload for `char` kicking in for that `operator <<` (which basically does nada on a nullchar, which is what you have). It is still be called, however. You can [see it live](https://godbolt.org/z/j943hGTeY) if you check the disassembly calls. – WhozCraig Mar 20 '22 at 04:26
  • 1
    @TWhite read about [default constructor](https://en.cppreference.com/w/cpp/language/default_constructor) and [zero initialization](https://en.cppreference.com/w/cpp/language/zero_initialization). `char()` is similar to `int()` or `long()` and produce the same value in the specified types. [Do built-in types have default constructors?](https://stackoverflow.com/q/5113365/995714), [Does "int a = int();" necessarily give me a zero?](https://stackoverflow.com/q/10100776/995714), [Do built-in types have default constructors?](https://stackoverflow.com/q/5113365/995714) – phuclv Mar 20 '22 at 07:30

1 Answers1

2

The fact that char() returns \0 is normal, and it's reliable (integer variables are initialized to 0 with such a syntax, and pointers are initialized to nullptr). For example, unsigned short int() will also returns 0. For a char, it's obviously not the character "0", but the NUL character.

Then, when trying to print that, you're trying to print a char that is used, in char* strings, to mark the end of the string... So without surprise, it isn't printed at all, even as a single character.

Wisblade
  • 1,483
  • 4
  • 13
  • 1
    *Isn't printed at all* is not correct. The NUL character is printed with the shown statement. It may be the case that the terminal does not show anything. But if you redirect the output to a file, you will notice that there is one byte in the file and that byte has the value zero. – j6t Mar 20 '22 at 08:27
  • @j6t We're not in the case of writing to a binary file, but to the _CONSOLE_... Which is particular, as you know it - for example, writing a TAB on a binary file is only the character 9, but on a console, it's (usually) between 1 and 8 spaces... – Wisblade Mar 20 '22 at 10:01