3

I want to do something like this in plain C:

struct data_msg {
    uint8_t id = 25;
    uint8_t       data1;
    uint32_t      data2;
}

I need the id to be set to 25 by default so that when I create an instance of the struct, the id is already set to 25, like this:

struct data_msg      tmp_msg;
printf("ID: %d", tmp_msg.id); // outputs ID: 25

Is there a way to do this in C? I know it can be done in C++, but have not figured a way in C.

Doing this in C will throw errors:

struct data_msg { uint8_t id = 25; }

Darth-CodeX
  • 2,166
  • 1
  • 6
  • 23
Dan
  • 33
  • 3
  • Does this answer your question? [How to initialize a struct in accordance with C programming language standards](https://stackoverflow.com/questions/330793/how-to-initialize-a-struct-in-accordance-with-c-programming-language-standards) – जलजनक Mar 30 '22 at 12:49
  • 1
    Remember struct is not a "class", because **C isn't OOP**. So you are creating a type. It would be the same if in the the definition of `int` you try to initialize always with the value 5. – Oscar Gonzalez Mar 30 '22 at 12:58

2 Answers2

5

Unfortunately, you can't, but if you do this a lot, you could create a constant that you use for initialization:

struct data_msg {
    uint8_t       id;
    uint8_t       data1;
    uint32_t      data2;
};

const struct data_msg dm_init = {.id = 25};

int main(void) {
    struct data_msg var = dm_init;  // var.id is now 25, data1 = 0, data2 = 0
    // ...
}
Ted Lyngmo
  • 93,841
  • 5
  • 60
  • 108
1

The C standard does not provide any feature for this. You may set initial values when defining an object, but there is no provision for setting default or initial values when defining a type.

Eric Postpischil
  • 195,579
  • 13
  • 168
  • 312