Is un-initialized integer always default to 0 in c?

External and static variables are initialized to zero by default, this is guaranteed. Automatic and register variables that do not have en explicit initializer will have an indeterminate value (either an unspecified value or a trap representation).

From The Standard:

C89

6.5.7:

If an object that has static storage duration is not initialized
explicitly, it is initialized implicitly as if every member that has
arithmetic type were assigned 0 and every member that has pointer type
were assigned a null pointer constant. If an object that has
automatic storage duration is not initialized explicitly, its value is
indeterminate.

C99

6.2.4, §5:

For such an object that does not have a variable length array type, its lifetime extends
from entry into the block with which it is associated until execution of that block ends in
anyway.(Entering an enclosed block or calling a function suspends, but does not end,
execution of the current block.) If the block is entered recursively,anew instance of the
object is created each time. The initial value of the object is indeterminate. If an
initialization is specified for the object, it is performed each time the declaration is
reached in the execution of the block; otherwise, the value becomes indeterminate each
time the declaration is reached.

6.7.8, §10:

If an object that has automatic storage duration is not initialized explicitly,its value is indeterminate. If an object that has static 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 orunsigned) zero;

— if it is an aggregate, every member is initialized (recursively) according to these rules;

— if it is a union, the first named member is initialized (recursively) according to these rules.

3.17.2, §1:

indeterminate value: either an unspecified value or a trap representation

3.17.3, §1:

unspecified value: valid value of the relevant type where this International Standard imposes no requirements on which value is chosen in any instance. NOTE An unspecified value cannot be a trap representation.

Leave a Comment