1

I am looking at some code that has this kind of struct definition in it. At first, I thought it was a special way of defining a struct that defined it and instantiated one at the same time. However, my predictions about how this type of code behaves were wrong after I tested some similar code myself. Can someone tell me what this code does/where I could look online to see a description of this kind of code?

struct Error e = { .code = 22,
                   .msg = 22100 };
N. Mao
  • 499
  • 1
  • 10
  • 19

3 Answers3

7

That's not a struct definition, it's a designated initializer. It's setting the code field to 22 and the msg field to 22100. Logically, you could rewrite it something like:

struct Error e = {0};
e.code = 22;
e.msg = 22100;

You can do something similar with arrays:

int a[5] = {
  [3] = 12,
  [4] = 17
};
Carl Norum
  • 219,201
  • 40
  • 422
  • 469
4

It's a C99 designation initializer.

Designation initializers allow you to initialize aggregate members in any order and they also allow you to omit members. Members that are not designated explicitly are initialized to 0.

For example, a initialization here:

struct bla {int x; int y; int z;};
struct bla a = {.x =1, .z = 1};

is equivalent to C89 initialization below:

struct bla a = {1, 0, 1};

A note on terminology, it's a designation initializer and not a designated initializer. See defect report DR#253:

"The tem "designated initializer" is never mentioned in the Standard though it appears in the index and new features section (the Standard uses the term "designation initializer" in the text).

ouah
  • 142,963
  • 15
  • 272
  • 331
  • That DR is incorrect. The phrase "designation initializer" does not appear in the standard. A *designation* can be part of an *initializer*. And since the phrase "designated initializer" *does* appear in the index and in the new features section, I'd say that's the correct term. – Keith Thompson Jul 03 '13 at 18:11
  • @KeithThompson *designation* is present in a lot of places in the Standard: for example *(C11, 6.5.2.5p10) EXAMPLE 3 Initializers with designations*, or *(6.7.9p7) "When no designations are present"*. Also syntax in 6.7.9 uses *designation_opt initializer*. – ouah Jul 03 '13 at 18:18
  • Yes, but the phrase "designation initializer" is not used, and in particular is not used to refer to what most of us call a "designated initializer". The syntax in 6.7.9 doesn't use it as a phrase; it's simply an optional *designation* followed by an *initializer*. – Keith Thompson Jul 03 '13 at 18:38
1

This is called a designated initializer, it's initializing an instance of the struct.

Here’s GCC’s manual page about how to use them.

s4y
  • 50,525
  • 12
  • 70
  • 98