Constructor for structs in C

前端 未结 6 1282
南旧
南旧 2021-02-01 01:48

Given:

struct objStruct {
    int id;
    int value;
};

typedef struct objStruct Object;

Is there a shortcut to allocate and initialize the ob

6条回答
  •  误落风尘
    2021-02-01 02:34

    In C99 and beyond, you can use a compound literal, which looks like a cast followed by an initializer in braces:

    int init_value = ...;
    int init_id    = ...;
    Object newObj1 = (Object){ .value = init_value, .id = init_id };
    Object newObj2 = (Object){ .id = init_id, .value = init_value };
    

    The latter two lines achieve the same effect - the order of the fields is not critical. That is using 'designated initializers', another C99 feature. You can create a compound literal without using designated initializers.

提交回复
热议问题