5

Here's the code:

#include <stdio.h>

int main (void)
{
    int value[10];
    int index;

    value[0] = 197;
    value[2] = -100;
    value[5] = 350;
    value[3] = value[0] + value[5];
    value[9] = value[5] / 10;
    --value[2];

    for(index = 0; index < 10; ++index)
        printf("value[%i] = %i\n", index, value[index]);
    return 0;
}

Here's the output when compile:

value[0] = 197
value[1] = 0
value[2] = -101
value[3] = 547
value[4] = 0
value[5] = 350
value[6] = 0
value[7] = 0
value[8] = 1784505816
value[9] = 35

I don't understand why value[8] returns 1784505816? Isn't value[8] supposed be = value[6] = value[7] = 0? By the way, I compile the code via gcc under Mac OS X Lion.

William Li
  • 55
  • 3

2 Answers2

20

value[8] was never initialized, therefore its contents are undefined and can be anything.

Same applies to value[1], value[4], value[6], and value[7]. But they just happened to be zero.

Mysticial
  • 464,885
  • 45
  • 335
  • 332
  • 8
    But if you used `int value[10] = {};`, then they would be zero-initialised. – C. K. Young Sep 22 '11 at 07:21
  • 5
    @ChrisJester-Young: You mean `{0}`. This is a C question. – CB Bailey Sep 22 '11 at 07:26
  • @CharlesBailey: +1 Wow, good call. I see that `{}` is a gcc extension (and when compiling with `-pedantic`, you get a "warning: ISO C forbids empty initializer braces" message). (It's too late for me to edit my comment now, alas.) – C. K. Young Sep 22 '11 at 07:29
  • 1
    `its contents are undefined`? The Standard uses the term *indeterminate*, not *undefined*. See this : [Fun with uninitialized variables and compiler (GCC)](http://stackoverflow.com/questions/4879045/fun-with-uninitialized-variables-and-compiler-gcc) – Nawaz Sep 22 '11 at 15:26
6

Objects with automatic storage duration declared without an initializer have indeterminate values until they are assigned to. Technically, it causes undefined behavior to use the value (e.g. printing int) of an object which has an indeterminate value.

If you want the array to be initialized to zero you need to provide an initializer. E.g.

int value[10] = {0};
CB Bailey
  • 755,051
  • 104
  • 632
  • 656