How to initialize a struct in accordance with C programming language standards

前端 未结 15 2653
予麋鹿
予麋鹿 2020-11-21 22:59

I want to initialize a struct element, split in declaration and initialization. This is what I have:

typedef struct MY_TYPE {
  bool flag;
  short int value;         


        
15条回答
  •  伪装坚强ぢ
    2020-11-22 00:01

    I have read the Microsoft Visual Studio 2015 Documentation for Initializing Aggregate Types yet, all forms of initializing with {...} are explained there, but the initializing with dot, named ''designator'' isn't mentioned there. It does not work also.

    The C99 standard chapter 6.7.8 Initialization explains the possibility of designators, but in my mind it is not really clear for complex structs. The C99 standard as pdf .

    In my mind, it may be better to

    1. Use the = {0};-initialization for all static data. It is less effort for the machine code.
    2. Use macros for initializing, for example

      typedef MyStruct_t{ int x, int a, int b; } MyStruct; define INIT_MyStruct(A,B) { 0, A, B}

    The macro can be adapted, its argument list can be independent of changed struct content. It is proper if less elements should be initialized. It is also proper for nested struct. 3. A simple form is: Initialize in a subroutine:

    void init_MyStruct(MyStruct* thiz, int a, int b) {
      thiz->a = a; thiz->b = b; }
    

    This routine looks like ObjectOriented in C. Use thiz, not this to compile it with C++ too!

    MyStruct data = {0}; //all is zero!
    init_MyStruct(&data, 3, 456);
    

提交回复
热议问题