Struct initialization of the C/C++ programming language?

前端 未结 5 1536
无人及你
无人及你 2020-11-27 21:46

I could do struct initialization with code:

struct struct_type_id struct_name_id = { value1, value2, value3 };

but could not with:

5条回答
  •  我在风中等你
    2020-11-27 22:19

    The first statement creates a variable initialized to the given values, i.e., these values are built in memory and stored directly in the program executable in that variable address (for globals) or ready for memory copy (for stack variables).

    The second statement of the second block is very different. Although it looks similar, it is an assign expression. It means that the RHS of the equals operator is an expression that is evaluated (independently of what is in the LHS of =), and then passed to the = operator. Without proper context, {...} doesn't have any meaning.

    In C99, you can do this:

    struct_name_id = (struct struct_type_id){ value1, value2, value3 };
    

    Now the RHS of the equals operator is a valid expression, since there is proper context for the compiler to know what is in {...}.

    In C++11, the syntax is:

    struct_name_id = struct_type_id{ value1, value2, value3 };
    

提交回复
热议问题