Is it better style to initialize a structure by passing a reference or returning it?

前端 未结 4 1836
栀梦
栀梦 2021-01-20 02:54

Say I have the following:

typedef struct {
    int x;
    int y;
    char a;
    char b;
} myStruct;

Is it better practice to create a new

4条回答
  •  -上瘾入骨i
    2021-01-20 03:01

    It depends on what you treat as initial state. For some people it means all zero, for other people it means a default state, or a meaningful state.

    Different defination of initial state you got different way to do it.

    For zeroing struct, you just do

    struct mystruc s = {0};
    

    If a struct requires specific value initialization, it may looks like:

    struct mystruc s = {1, 2, NULL, 0x1234};
    

    For non-trival initialization, I personally like this:

    struct mystruc s;
    if ( mystruc_init(&s) < 0 ) it_is_fail();
    

    IMO, your second method myStruct s = init(); does not enforce initialization any more than the above methods, programmer may still do myStruct s; without getting warnings, and I personally hate returning local variable of complicated data type.

提交回复
热议问题