This blog is under construction

Sunday, 6 May 2012

Array initialization at compile time

Arrays can be initialized either at compile time or at run time.

Syntax:
     data_type array_name[subscript] = {values};

     Eg: int num[5] = {1, 2, 3, 4, 5};

The above statement initializes value for all the elements of the array at compile time.

Lets see few complicated array initialization.
int num[5] = {1, 2, 3};
The above statement initializes first 3 elements of the array, and then it sets the value of last two elements to 0.

int num[5] = {[1]10, [3]20};
The above statement assigns 10 and 20 to second and fourth element of the array, and then it sets 0 to all the other elements.

int num[5] = {[1] = 10, [3] = 20};
The above statement assigns 10 and 20 to second and fourth element of the array, and then it sets 0 to all the other elements.

int num[5] = {[0...2] = 1, [4] = 4};
The above statement assigns 1 to the first 3 elements of the array, 4 to the last element of the array and 0 to the fourth element of the array.

int num[] = {10, 20, 30, 40, 50};
The above statement indicates that there are 5 elements in the array and all the elements of the array are initialized(num[0] = 10, num[1] = 20, num[3] = 40, num[4] = 50). If we are going to initialize all the elements of the array during declaration, then we don't need to explicitly specify array index as shown above.

Example C program on array declaration

#include <stdio.h> 
  int main() {
        int i, arr1[5] = {1, 2, 3, 4, 5};
        int arr2[5] = {1, 2, 3};
        int arr3[5] = {[2]10, [4]20};
        int arr4[5] = {[2] = 10, [4] = 20};
        int arr5[5] = {[0 ... 2] = 1, [4] = 4};
        int arr6[ ] = {10, 20, 30, 40, 50};

        /* printing the values of arr1 and arr2 */
        for (i = 0; i < 5; i++) {
                printf("arr1[%d]: %d\tarr2[%d]: %d\n", i, arr1[i], i, arr2[i]);
        }
        printf("\n");

        /* printing the values of arr3 and arr4 */
        for (i = 0; i < 5; i++) {
                printf("arr3[%d]: %d\tarr4[%d]: %d\n", i, arr3[i], i, arr4[i]);
        }
        printf("\n");

        /* printing the values of arr5 and arr6 */
        for (i = 0; i < 5; i++) {
                printf("arr5[%d]: %d\tarr6[%d]: %d\n", i, arr5[i], i, arr6[i]);
        }
        return 0;
  }

  Output:
  jp@jp-VirtualBox:~/$ ./a.out
  arr1[0]: 1      arr2[0]: 1
  arr1[1]: 2      arr2[1]: 2
  arr1[2]: 3      arr2[2]: 3
  arr1[3]: 4      arr2[3]: 0
  arr1[4]: 5      arr2[4]: 0

  arr3[0]: 0      arr4[0]: 0
  arr3[1]: 0      arr4[1]: 0
  arr3[2]: 10    arr4[2]: 10
  arr3[3]: 0      arr4[3]: 0
  arr3[4]: 20    arr4[4]: 20

  arr5[0]: 1      arr6[0]: 10
  arr5[1]: 1      arr6[1]: 20
  arr5[2]: 1      arr6[2]: 30
  arr5[3]: 0      arr6[3]: 40
  arr5[4]: 4      arr6[4]: 50



No comments:

Post a Comment