cc99compound-literals

Typing of Array in C structure is "overflowing" into subsequent fields?


I have the following types:

typedef float vec4[4]; // from cglm
typedef struct Node Node;
struct Node {
    float expand;
    vec4 color;
    Node *children;
}

For some reason, the color field's float[4] type is.. overflowing? into the fields after it. For example, when using the following literal:

Node test1 = (Node) { 
   .expand = 1.0f,
   .color = (vec4) { 0, 0, 1, 1 },
   .children = NULL
};

The compiler thinks that the color and children fields both ought to be single floats?:

How do I properly provide the float[4] value within this structure literal, without breaking subsequent fields?


Solution

  • (vec4) { 0, 0, 1, 1 } is a compound literal that is indeed an array. However, you cannot initialize an array using an array (except for string literals), just as you cannot assign an array to an array. Arrays have never been first-class objects in C that can be operated on as a single thing; they have always been an aggregate of multiple things. Additionally, compound literals were added to the language late.

    The grammar for initializing an array is to list the initial values of its elements in braces. So simply change .color = (vec4) { 0, 0, 1, 1 }, to .color = { 0, 0, 1, 1 },.