1

Does C guarantees that an unsigned integer field inside a struct gets initialized to zero? In my system, it seems it does (or I am very "lucky"(actually unlucky)).

In code words, what will happen in the following scenario?

struct node {
  unsigned int rec_size;
};

struct node node;
// what is the value of node.rec_size? Undefined or 0?

Relevant answer, but not the same, since in my example, there is only one field and no initialization.

Community
  • 1
  • 1
gsamaras
  • 71,951
  • 46
  • 188
  • 305

2 Answers2

7

The answer is, it depends on the storage-class:

If it is _Thread_local or static, it is guaranteed to be zeroed.

If it is auto or dynamic storage, no initialization takes place.

6.7.9 Initialization

10 If an object that has automatic storage duration is not initialized explicitly, its value is indeterminate. If an object that has static or thread storage duration is not initialized explicitly, then:

  • if it has pointer type, it is initialized to a null pointer;
  • if it has arithmetic type, it is initialized to (positive or unsigned) zero;
  • if it is an aggregate, every member is initialized (recursively) according to these rules, and any padding is initialized to zero bits;
  • if it is a union, the first named member is initialized (recursively) according to these rules, and any padding is initialized to zero bits;

BTW: Zero-initialization in C++ is equivalent to those rules for static/thread-local objects.

Deduplicator
  • 44,692
  • 7
  • 66
  • 118
  • 2
    Yes, C has an `auto` keyword. http://stackoverflow.com/questions/2192547/where-is-the-c-auto-keyword-used – gsamaras Oct 17 '14 at 14:32
  • 3
    `auto` is the keyword (introduced for symmetry at the beginning of time), marking auto-storage-class objects (function-local, no explicit storage-class aka stack-allocated). And yes, in C++11 they finally got around to remove those semantics in C++ replace them with type-deduction-semantics (Stroustroup already wanted to do that in C-with-classes ages ago). – Deduplicator Oct 17 '14 at 14:32
  • 1
    @wolfPack88: Ah, to be young!! – Lightness Races in Orbit Oct 17 '14 at 14:55
5

No, the value is undetermined.

Value will be 0 only if the variable is static or global.

2501
  • 25,460
  • 4
  • 47
  • 87