Search code examples
carraysinitializationdesignated-initializer

Evaluation of a statement in C language


struct 
{
    int a[2], b;
} 
arr[] = {[0].a = {1}, [1].a = {2}, [0].b = 1, [1].b = 2};

How to evaluate this line in C language? General declaration of struct is different from this statement. Also accessing of an element in C can be done like [0].a , [0].b like this?


Solution

  • First lines are the definition of a new structure type:

    struct {
       int a[2], b;
    }
    

    It declares a structure with two members: an array of two ints named a and an int b.

    Next can be decomposed as the following, first the variable:

    arr[]
    

    which defines a variable arr that is an array of structures. The size of the array is not defined because the variable is initialized (and so its size defined by this initialization) by:

    { [0].a = ... }
    

    This is a new C (C99, which not so new...) syntax to initialize contents of structured data types: designated initializer.

    As you are initializing something the context of what you are initializing is defined (array of structure with two members). Then notation [0] just references the first member of the array (so array have at least one element), and as this element is structured [0].a denotes its member a, itself an array. Then this array is initialized too by { 1 }. Here the trick is that the length of this array member is already defined by the type definition: length 2, then { 1 } initializes that array with the first element equals to 1 and the second with 0 (default value for initialization of ints). Etc.

    At the end:

    {[0].a = {1}, [1].a = {2}, [0].b = 1, [1].b = 2};
    

    initializes arr as:

    1. an array of length 2
    2. its first element member a initialized to 1,0 and its member b initialized to 1
    3. its second element member a initialized to 2,0, and its member b initialized to 2

    If you use assignements then you could have write something like:

    struct { ... } arr[2];
    arr[0].a[0] = 1;
    arr[0].a[1] = 0;
    arr[0].b = 1;
    arr[1].a[0] = 2;
    arr[1].a[1] = 0;
    arr[1].b = 2;
    

    Where [0] (for example) denotes the first element of an array but needs to be prefixed with an expression that denotes that array, so arr[0]...