What is special about structs?

前端 未结 4 492
走了就别回头了
走了就别回头了 2021-01-30 16:03

I know that in C we cannot return an array from a function, but a pointer to an array. But I want to know what is the special thing about structs that makes them re

4条回答
  •  渐次进展
    2021-01-30 16:06

    There isn't anything special about struct types; it's that there's something special about array types that prevents them from being returned from a function directly.

    A struct expression is treated like an expression of any other non-array type; it evaluates to the value of the struct. So you can do things like

    struct foo { ... };
    
    struct foo func( void )
    {
      struct foo someFoo;
      ...
      return someFoo;
    }
    

    The expression someFoo evaluates to the value of the struct foo object; the contents of the object are returned from the function (even if those contents contain arrays).

    An array expression is treated differently; if it's not the operand of the sizeof or unary & operators, or if it isn't a string literal being used to initialize another array in a declaration, the expression is converted ("decays") from type "array of T" to "pointer to T", and the value of the expression is the address of the first element.

    So you cannot return an array by value from a function, because any reference to an array expression is automatically converted to a pointer value.

提交回复
热议问题