3

Every variable should be properly defined and initialized(assign a value to it) before being used. However under some circumstances, c++ will set variables with a default value of zero. Like the case below.

class A{
    ...
    static int val;
    ...};

//int val = 10; //This is the usual definition.
int val;//Definition without assigning a value.
...
A a;  //a class A object
std::cout<<a.val;

The result would be zero. Obviously, the compiler did something to initialize variable a.val to zero. I am curious about when will they do this generally?

richard.g
  • 3,585
  • 4
  • 16
  • 26

1 Answers1

8

http://en.cppreference.com/w/cpp/language/zero_initialization

Zero initialization is performed in the following situations:

  1. For every named variable with static or thread-local storage duration, before any other initialization.
  2. As part of value-initialization (i.e. with an empty pair of parentheses or braces) sequence for non-class types and for members of value-initialized class types that have no constructors.
  3. When a character array is initialized with a string literal that is too short, the remainder of the array is zero-initialized.
Community
  • 1
  • 1
Pavel Anossov
  • 60,842
  • 14
  • 151
  • 124
  • 3
    The last line is dubious. Character arrays are treated the same as all other arrays. `int a[2] = { 2 }` initializes `a[1]` to zero. – MSalters Dec 05 '13 at 15:27
  • @MSalters The last line was from `§8.5.2[dcl.init.string]/3` (C++11) – Cubbi Dec 05 '13 at 18:31
  • @MSalters item 3 mentions specifically *initialized with a string literal*, i.e. `"abc"`, not with an array initializer like `{'a', 'b', 'c'}`, so it is indeed a special case for character arrays. – Colin D Bennett Jul 29 '14 at 17:18