1

According to C++ Primer (4th Edition) by Stanley Lipmann, on page 50 it says:

"Variables defined outside any function body are initialized to 0."

Based on what I read it seems it is not true.

A global char is default to blank and not 0.

Would appreciate any help.

David G
  • 94,763
  • 41
  • 167
  • 253
yapkm01
  • 3,590
  • 7
  • 37
  • 62

3 Answers3

9

Stanley is correct — objects with static storage duration are zero-initialised before any other initialisation takes place.

So, in your terminology, a global char is "defaulted" to 0. This is the integer 0, and not the character '0' (which is usually 48). When you try to stream it to a console, you won't see anything, as this char value has no human-readable representation.

If you meant a global char* or char const*, then this is also "defaulted" to 0, i.e. it will be a null pointer. This is not the same as a pointer to an empty string. Trying to stream this will result in undefined behaviour, so you could see nothing or you could see my Mum's recipe for tomato soup presented in the form of interpretive dance at 20Hz behind an ASCII art translation layer.

Neither will be "blank", though without knowing what "blank" means here I cannot say that with absolute certainty.

Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055
6

Try this:

#include <iostream>
char global;

int main()
{
    std::cout << "Value of Global " << ((int)global) << "\n";
}

global here is a static storage duration object and as such will be zero initialized.
I cast it (very lazily) to an integer so that the stream will print out its value (rather than the character) just to show that it is zero.

Printing out the char '\0' is not going to print anything useful.

Martin York
  • 257,169
  • 86
  • 333
  • 562
  • Printing out the char `'\-'` is undefined behavior, unless the stream was opened in binary mode (which isn't the case for `std::cout`). – James Kanze Dec 22 '12 at 22:13
3

'0' is not 0. When it states initialized to 0 it means the value 0 (which is also \0 or NULL), not the character '0' (which is 48 in ASCII encoding).

Jack
  • 131,802
  • 30
  • 241
  • 343