To declare and initialize ANSI Structure separately?

Asked 2 years ago, Updated 2 years ago, 200 views

How can I declare and initialize the structure in a different place?

For example, in this code,

typedef struct MY_TYPE {
  boolean flag;
  short int value;
  double stuff;
} } MY_TYPE;

void function(void) {
  MY_TYPE a;
  ...
  a = { true, 15, 0.123} // Like this
}

How do I initialize a member variable within MY_TYPE in ANSI C (C89, C90, C99, C11 etc.)?

If you want to separate declaration and initialization,

a.flag = true;
a.values = 15;

Is there no choice but to designate everything like this?

c struct initialization

2022-09-22 22:22

1 Answers

At ANSI C99, MY_TYPE a = { .flag = true, .value = 123, .stuff = 0.456 }; A variable that can be written together and that you do not specify is initialized to zero.

This is called designated initializer.

For more information, see Designed Initiators.


2022-09-22 22:22

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.