C++: Are local automatic variables initialized or not? Stroustrup example

Viewed 226

The following example is from Stroustrup C++ 4th Ed. Page 519. It was my understanding from K&R C and earlier in the Stroustrup book that local automatic variables of primitive types are undefined or not known to be initialized. Static variables of primitive types or automatic variables of a class with a default constructor are initialized.

That would mean int b should be undefined and not known to be initialized. Yet, Stroustrup adds the following code comment saying b = 0. Is this Errata? Or perhaps some behavior of calling with the default constructor?

Thank you

struct S { 
   string a;
   int b;
};

void f(void) {
   S s0 {}; // default construction: {"",0}
   // ...
}
3 Answers

It's easy. You can leave the built-in type variables uninitialized or you can ask the compiler to zero-initialize them.

S s1;   // string is default initialized, int is left uninitialized
S s2{}; // All fields are initialized.

Notice the {}. That (in this case) asks the compiler to initialize all fields.

In this line:

S s0 {};

the syntax that is used is value-initialization, in particular

  1. when a named variable (automatic, static, or thread-local) is declared with the initializer consisting of a pair of braces.

In this case, the effect of value-initialization is that the object s0 is zero-initialized.

In this particular case, the effect is:

If T is an non-union class type, all base classes and non-static data members are zero-initialized, and all padding is initialized to zero bits. The constructors, if any, are ignored.

which implies that the int member b is zero-initialized to the value 0.

Are local automatic variables initialized or not?

It depends on the initialisation syntax that is used, the type of the variable, as well as the storage class.

That would mean int b should be undefined

No, because the example uses value initialisation, and the class in question is an aggregate.

Related