How does the compiler fill values in char array[100] = {0};
? What's the magic behind it?
I wanted to know how internally compiler initializes.
How does the compiler fill values in char array[100] = {0};
? What's the magic behind it?
I wanted to know how internally compiler initializes.
If your compiler is GCC you can also use following syntax:
Please look at http://gcc.gnu.org/onlinedocs/gcc-4.1.2/gcc/Designated-Inits.html#Designated-Inits, and note that this is a compiler-specific feature.
It depends where you put this initialisation.
If the array is static as in
then it is the compiler that reserves the 100 0 bytes in the data segement of the program. In this case you could have omitted the initialiser.
If your array is auto, then it is another story.
In this case at every call of the function foo you will have a hidden memset.
The code above is equivalent to
and if you omit the initializer your array will contain random data (the data of the stack).
If your local array is declared static like in
then it is technically the same case as the first one.
It's not magic.
The behavior of this code in C is described in section 6.7.8.21 of the C specification (online draft of C spec): for the elements that don't have a specified value, the compiler initializes pointers to NULL and arithmetic types to zero (and recursively applies this to aggregates).
The behavior of this code in C++ is described in section 8.5.1.7 of the C++ specification (online draft of C++ spec): the compiler aggregate-initializes the elements that don't have a specified value.
Also, note that in C++ (but not C), you can use an empty initializer list, causing the compiler to aggregate-initialize all of the elements of the array:
As for what sort of code the compiler might generate when you do this, take a look at this question: Strange assembly from array 0-initialization
Implementation is up to compiler developers.
If your question is "what will happen with such declaration" - compiler will set first array element to the value you've provided (0) and all others will be set to zero because it is a default value for omitted array elements.