Search code examples
cgccdesignated-initializer

Is there an alternative to Range Initialization of arrays in C?


I believe it's a simple question: Is there a way to initialize an array with values that are nonzero without using loops?

One way I know is to use Range Initialization to initialize the array with the values I want. For example:

int main()
{
   /* Using Designated Range Initialization*/
   int my_array[10] = {[0 ... 3] = 5, [4 ... 7] = 15, [8 ... 9] = 30};
   /* Using Explicit initialization for each element */
   int other_array[10] = {5, 5, 5, 5, 15, 15, 15, 15, 30, 30};

   return 0;
}

However, this method is just an extension of the GCC compiler, and not part of ISO C. So given this possible non-portability between systems, is there a way to do an array initialization in a similar way? Of course, without using loops.

Also, the method I'm looking for is just beyond the explicit initialization of each element of the array.


Solution

  • Code needs to explicitly initialize the non-zero array elements.

    Could use macro magic if there is a pattern:

    #define ONE(x) (x), (x)+1, (x)+2, (x)+3, (x)+4, (x)+5, (x)+6, (x)+7, (x)+8, (x)+9
    #define TEN(x) ONE(x),ONE((x)+10),ONE((x)+20),ONE((x)+30),ONE((x)+40), \
        ONE((x)+50),ONE((x)+60),ONE((x)+70),ONE((x)+80),ONE((x)+90)
    
    int main() {
      int count[100] = { TEN(1) };
      printf("%d %d\n", count[0], count[99] );
    }
    

    Output

    1 100
    

    Example for OP

    #define X2(x) (x), (x)
    // Note the nested macro
    #define X4(x) X2(x), X2(x)
    #define X8(x) X4(x), X4(x)
    #define X10(x) X8(x), X2(x)
    #define X16(x) X8(x), X8(x)
    // ....
    
    
    int main()
    {
       int my_array[10] = { X4(5), X4(15), X2(30)};
       printf("%d %d\n", my_array[0], my_array[9] );
       return 0;
    }
    

    Output

    5 30