6

Is it possible to statically initialise part of a struct?

The stuct I have:

   struct data {
    char name[20];
    float a;
    int b;
    char c;
};

When initialsing and printing:

struct data badge = {"badge",307};
printf("%s,%d\n", badge.name, badge.b);

This will print out "badge", but not '307'.

How can I get this to use char name[20] and int b whilst ignoring float a.

  • 3
    how can you assume that 307 will be put in b in the first place? how can the compiler know that, if you don't specify it? you were thinking about type matching for sure.. but remember 307 will be cast to a float implicitely easily. – Willi Mentzel Aug 05 '16 at 11:25
  • 4
    Note that the struct will be fully initialized if any part of it is initialized. The parts you did not initialize explicitly will be zero-initialized implicitly like objects with static storage duration. – EOF Aug 05 '16 at 11:26

2 Answers2

8

You can use C99's designated initializers as suggested by @sps:

struct data badge = {.name = "badge", .b = 307};

But in C89, there's no way to initialise only certain members of a struct. So, you'd have to do:

struct data badge = {"badge", 0.0, 307, 0};

Notice even with designated initializers, members which are not explicitly initialized will be zero initialized. So, both of the above are equivalent.

But with designated initializers you don't have explicitly initialize it (imagine if you have struct with 100 members and you want to provide an initial for only 2 of them -- like in your example) and makes the code easier to read as well.

Dean P
  • 1,841
  • 23
  • 23
P.P
  • 117,907
  • 20
  • 175
  • 238
  • 2
    this is a more complete answer, as it states other members are zero initialized. – sps Aug 05 '16 at 11:41
3

You can do,

 struct data badge = {.name = "badge", .b = 307};
sps
  • 2,720
  • 2
  • 19
  • 38