-1

I'm new to C. If I write:

long  my_array[100]; // global variable

Does C initialize the values to zero, or do I have to it manually initialize to zero?

user836026
  • 10,608
  • 15
  • 73
  • 129
  • it creates an empty array with the length of 100. No values are given. – Chris Mar 03 '16 at 23:54
  • 1
    Yes, for global variables it's automatically initialised to 0. It's defined by the C standard and not specific to GNU. – kaylum Mar 03 '16 at 23:55
  • If it is globally or statically declared, it is initialised to 0. Otherwise it is not initialised unless by you. – Weather Vane Mar 03 '16 at 23:55
  • If it is an automatic or locally declared variable, you must initialise it, but you don't need to do it all. Even if you initialise only the first element, the rest get initialised to 0. `long my_array[100] = { 0,};` – Weather Vane Mar 03 '16 at 23:58

2 Answers2

3
  • Global variables are automatically zero-filled (and do not need to be initialized if this is the intent). It is required by the standard (§6.7.8/10).

  • The standard for uninitialized static objects in section 6.7.8.10 of the C99 standard says:

"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."
3

It depends on the context.

If the array is declared with static storage duration (in file scope or in block scope with explicit keyword static), then it is guaranteed to be zero-initialized. Otherwise, it is not initialized at all.

You have not provided any context. However, the comment suggests that this is supposedly a "global variable", which implies that it is declared in file scope. If so, it is zero-initialized.

AnT stands with Russia
  • 312,472
  • 42
  • 525
  • 765