开发者

C Struct initialization : strange way

While reading a code I came across, the following definition and initialization of a struct:

// header file
struct foo{
char* name;
int value;
};

//Implementation file
struct foo fooElmnt __foo;
// some code using fooElmnt
struct foo fooElmnt __f开发者_运维技巧oo = {
    .name = "NAME";
    .value = some_value;
}

What does this mean in C and how is it different from usual declarations?


It's called designated initialization,

In a structure initializer, specify the name of a field to initialize with .fieldname = before the element value. For example, given the following structure,

 struct point { int x, y; };

the following initialization

 struct point p = { .y = yvalue, .x = xvalue };

is equivalent to

 struct point p = { xvalue, yvalue };

If you read on, it explains that .fieldname is called a designator.

UPDATE: I'm no C99 expert, but I couldn't compile the code. Here's the changes I had to make:

// header file
struct foo{
char* name;
int value;
};

//Implementation file
//struct foo fooElmnt __foo;
// some code using fooElmnt
struct foo fooElmnt  = {
    .name = "NAME",
    .value = 123
};

Were you able to compile it? I used TCC.


Those are designated initializers, introduced in c99. You can read more here

Without them, you'd use

struct foo fooElmnt __foo = {
    "NAME",
    some_value
};

While in this case it doesn't matter much - other than the c99 way is more verbose, and its easier to read which element is initialized to what.

It does help if your struct has a lot of members and you only need to initialize a few of them to something other than zero.


This is a designated initialization. This also initializing the fields by their name, which is more readable than anomynous initialization when the structures are getting large. This has been introduced by the C99 standard.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜