initial value of int array in C

Viewed 113463

When declaring an array in C like this:

int array[10];

What is the initial value of the integers?? I'm getting different results with different compilers and I want to know if it has something to do with the compiler, or the OS.

10 Answers

The relevant sections from the C standard (emphasis mine):

5.1.2 Execution environments

All objects with static storage duration shall be initialized (set to their initial values) before program startup.

6.2.4 Storage durations of objects

An object whose identifier is declared with external or internal linkage, or with the storage-class specifier static has static storage duration.

6.2.5 Types

Array and structure types are collectively called aggregate types.

6.7.8 Initialization

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 or unsigned) 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.

It depends from the location of your array. if it is global/static array it will be part of bss section which means it will be zero initialized at run time by C copy routine. If it is local array inside a function, then it will be located within the stack and initial value is not known.

if array is declared inside a function then it has undefined value but if the array declared as global one or it is static inside the function then the array has default value of 0.

Related