5

Ain't gonna speak for other compilers, but in GNU GCC compiler you can statically initialize array with the following syntax:

struct some_struct {
        unsigned *some_array;
} some_var = {
        .some_array = (unsigned[]) { 1u, 2u, 3u, 4u, 5u, },
};

First I've met this syntax searching for the answer of a question I was concerned and came to this answer. But I've not found any link to GNU reference which covers this kind of syntax yet.

I'd be very grateful if someone share me a link on this syntax. Thank you!

Community
  • 1
  • 1
mesmerizingr
  • 1,417
  • 1
  • 18
  • 25

2 Answers2

2

Well, if your question is about compound literal syntax, then one important detail here is that you are not initializing an array within a structure. You are initializing a pointer within a structure. The code that you have now is formally correct.

If you really had an array inside your structure, then such initialization with a compound literal would not work. You cannot initialize an array from another array. Arrays are not copyable (with the exception of char array initialization from string literal). However, in that case you'd be able to use an ordinary {}-enclosed initializer, not a compound literal.

Also keep in mind that the lifetime of the compound literal (unsigned[]) { 1u, 2u, 3u, 4u, 5u, } is determined by the scope in which it appears. If you do the above in local scope, the compound literal array will be destroyed at the end of the block. The pointer value (if you somehow manage to take it outside that block) will become invalid.

AnT stands with Russia
  • 312,472
  • 42
  • 525
  • 765
1

You won't likely find much GNU documentation on this because it is not a GCC extension - this is a part of standard C syntax called a compound literal. It is defined in the C standard, in sections 6.5.2.5 and 6.7.9 (the latter covers the part between the braces, which is the same for both compound literals and static initialisers, so the standard only describes it once).

You can use this syntax to describe dynamic object values as well, not just for static initialisations, even standing alone in an expression without having been assigned to any variable. A compound literal can appear essentially anywhere a variable name can appear: you can pass them to functions, create them just to access one element, take their address (you can even assign to them, although it's not obvious how that's useful).

The syntax is uniform across all C value types and can be used to create arrays (designate specific elements to set with [N]=), structs and unions (designate specific elements with .field=) and even numeric types (no elements, so don't designate, just put the value between the braces). The syntax is intended to be simple and consistent for macros and code generators to produce (in addition to being elegant to write by hand).

Alex Celeste
  • 12,824
  • 10
  • 46
  • 89