0

I came across some C code with an unusual structure initialization syntax.

struct spi_ioc_transfer tr = {
    .tx_buf = (unsigned long)tx,
    .rx_buf = (unsigned long)rx,
    .len = ARRAY_SIZE(tx),
    .delay_usecs = delay,
    .speed_hz = speed,
    .bits_per_word = bits,
};

First off, I have no idea what this is called. What is this known as? Perhaps "dot initialisation syntax" as I suggested in the question title? I have not encountered this before so I don't know how to describe it.

Secondly, this is valid C code as it compiles, however what dialect of C is this and when was it introduced? (Was it new in C11?)

Thirdly, if some members of the struct are omitted, are those members initialized to zero. If not, is there a way to initialize the struct such that omitted members are zero.

(For example spi_ios_transfer also contains a field cs-change which has been omitted here.)

Finally is this permitted also in C++, and does it work with C++ classes?

FreelanceConsultant
  • 13,167
  • 27
  • 115
  • 225
  • 1
    This is a "designated initializer": https://en.cppreference.com/w/c/language/struct_initialization – UnholySheep Aug 13 '21 at 10:11
  • This is one of *designator*. [N1256](http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1256.pdf) (C99) has that (6.7.8 Initialization), but [C89](http://port70.net/~nsz/c/c89/c89-draft.html#3.5.7) doesn't seem having that. – MikeCAT Aug 13 '21 at 10:13

1 Answers1

2

First off, I have no idea what this is called.

Designated initializer

Secondly, this is valid C code as it compiles, however what dialect of C is this and when was it introduced? (Was it new in C11?)

C99 and later

Thirdly, if some members of the struct are omitted, are those members initialized to zero.

Yes

Finally is this permitted also in C++, and does it work with C++ classes?

It was introduced in C++20

klutt
  • 30,332
  • 17
  • 55
  • 95