I am having a difficult time understanding why initializing an array with a literal size e.g. int arr[3];
, yields a different behavior from an array initialized to a size of a constant like int arr[SOME_CONST];
that is set to 3.
When the size of the array is provided as a literal, it behaves as expected:
int arr[3];
//initialize the first two elements of the array, leave the third element uninitialized.
arr[0] = 1;
arr[1] = 2;
//print all elements of array
printf("arr[0]: %d\n", arr[0]);
printf("arr[1]: %d\n", arr[1]);
printf("arr[2]: %d\n", arr[2]);
Output:
arr[0]: 1
arr[1]: 2
arr[2]: 0
As you can see in the output the value of the uninitialized element arr[2]
is 0
just as expected.
The behavior becomes unexpected when the array size is defined as a constant, like so:
const int SOME_CONST = 3;
int arr[SOME_CONST];
//initialize the first two elements of the array, leave the third element uninitialized.
arr[0] = 1;
arr[1] = 2;
//print all elements of array
printf("arr[0]: %d\n", arr[0]);
printf("arr[1]: %d\n", arr[1]);
printf("arr[2]: %d\n", arr[2]);
Output:
arr[0]: 1
arr[1]: 2
arr[2]: 32766
Now the uninitialized element arr[2]
has a seemingly random value of 32766
Could someone help me understand why the two cases behave differently.
I've created two snippets on ideone to demonstrate this behavior as well.