0

I wonder the meaning of attribute definitions with dot (.) for struct attributes in Redis source code :

    struct config cfg = {
      .tcp = {
        .host = "127.0.0.1",
        .port = 6379
      },
      .unix = {
        .path = "/tmp/redis.sock"
      }
    };

Does it have a special meaning when you define an attribute with dot like .tcp = {...} ?

Thanks all.

tugcem
  • 1,078
  • 3
  • 14
  • 25
  • 1
    I believe this is a duplicate question, see here: http://stackoverflow.com/questions/8047261/what-does-dot-mean-in-a-struct-initializer?lq=1 Also relevant: http://stackoverflow.com/questions/330793/how-to-initialize-a-struct-in-ansi-c?lq=1 – mwjohnson Aug 14 '13 at 00:57
  • Thanks for redirection! – tugcem Aug 14 '13 at 01:04

2 Answers2

1

It is a way to do named initialization of the struct members.

The default way to initialize a struct requires you to provide the arguments in the order the members were defined. This lets you you reorder that, and makes it more readable as well. This syntax also lets you initialize only a few members of the struct, esp. if they are not the first few. Take a look at this page.

Karthik T
  • 31,456
  • 5
  • 68
  • 87
  • Good to know. So designated initialization is especially used for partial initialization in any order you like. Thanks! – tugcem Aug 14 '13 at 01:03
  • @TuğcemOral, his answer is incomplete. I am adding a full one, he's missing an important point. – Jacob Pollack Aug 14 '13 at 01:20
0

... I wonder the meaning of attribute definitions with dot (.) for struct attributes ...

It allows for you to access a specific element of the structure using the initialization syntax { }. For example, consider this struct:

struct my_struct {
  int field_1;
  int field_2;
  int field_3;
};

... it can be initialized as follows:

struct my_struct s1 = { 1, 2, 3 };

... or as follows:

struct my_struct s2 = { .field_1 = 1, .field_2 = 2, .field_3 = 3 };

... or if you do not know the order of the fields (or want to specify them in some order):

struct my_struct s3 = { .field_3 = 3, .field_1 = 1, .field_2 = 2 };

... remark that s1 is equivalent to s2 which is equivalent to s3. Moreover, if you do not specify a field in your initialization then it will be zero. From the C99 standard 6.7.8.21:

If there are fewer initializers in a brace-enclosed list than there are elements or members of an aggregate, or fewer characters in a string literal used to initialize an array of known size than there are elements in the array, the remainder of the aggregate shall be initialized implicitly the same as objects that have static storage duration.

... to illustrate this:

struct my_struct s4 = { .field_1 = 1 };

... that will zero-fill fields 2 and 3, hence s4.field_2 == 0 implies true.

Jacob Pollack
  • 3,703
  • 1
  • 17
  • 39