1-D Array - Compile Time Initializing : C Programming
Different Methods of 1-D Array - Compile Time Initializing
Whenever we declare an array we can initialize array directly at compile time. Initialization of an array is called as compiler time initialization if and only if we assign certain set of values to array element before executing program. i.e at Compilation Time.
Different Ways Of Array Initialization :
- Size is Specified Directly
- Size is Specified Indirectly
A. Method 1 : Array Size Specified Directly
In this method , we try to specify the Array Size directly.
int num[5] = {2,8,7,6,0};
In the above example we have specified the size of array as 5 directly in the initialization statement.Compiler will assign the set of values to particular element of the array.
num[0] = 2 num[1] = 8 num[2] = 7 num[3] = 6 num[4] = 0
As at the time of compilation all the elements are at Specified Position So This Initialization Scheme is Called as “Compile Time Initialization“.
Graphical Representation :
B. Method 2 : Size Specified Indirectly
In this scheme of compile time Initialization, We does not provide size to an array but instead we provide set of values to the array.
int num[] = {2,8,7,6,0};
Explanation :
- Compiler Counts the Number Of Elements Written Inside Pair of Braces and Determines the Size of An Array.
- After counting the number of elements inside the braces, The size of array is considered as 5 during complete execution.
- This type of Initialization Scheme is also Called as “Compile Time Initialization“
Live Example :
#include <stdio.h> int main() { int num[] = {2,8,7,6,0}; int i; for(i=0;i<5;i++) { printf("\nArray Element num[%d] : %d",i+1,num[i]); } return 0; }
Output :
Array Element num[1] : 2 Array Element num[2] : 8 Array Element num[3] : 7 Array Element num[4] : 6 Array Element num[5] : 0