Constructor for structs in C

前端 未结 6 1212
南旧
南旧 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:48

    In C it is possible to declare an inline function with the same name as structure:

    struct my
    {
        int a;
    };
    
    inline struct my* my(int* a)
    {
        return (struct my*)(a);
    }
    
    //somewhere in code
    int num = 123;
    struct my *sample = my(&num);
    //somewhere in code
    

    It looks pretty similar to C++ ctors.

提交回复
热议问题