Why structs cannot be assigned directly?

后端 未结 2 1087
半阙折子戏
半阙折子戏 2021-01-01 10:45

Suppose I have a fully defined struct with tag MyStruct, and suppose that x, y, ..., z are allowed values for its fields. Why is

st         


        
相关标签:
2条回答
  • 2021-01-01 11:38

    You can do this, but you need to supply the type of the structure before your aggregate:

    struct MyStruct q;
    q = (struct MyStruct){x,y,...,z};
    
    0 讨论(0)
  • 2021-01-01 11:46

    What you are looking for is a compound literal. This was added to the language in C99.

    Your first case:

    struct MyStruct q = {x,y,..,z};
    

    is a syntax specific to initialization. Your second case, in the pedantics of the language is not initialization, but assignment. The right hand side of the assignment has to be a struct of the correct type. Prior to C99 there was no syntax in the language to write a struct literal, which is what you are trying to do. {x,y,..,z} looked like a block with an expression inside. If one were inspired to try to think of it as a literal value, though the language didn't, one couldn't be sure of its type. (In your context, you could make a good guess.)

    To allow this and resolve the type issue, C99 added syntax so you could write:

    q = (struct MyStruct){x,y,...,z};
    
    0 讨论(0)
提交回复
热议问题