How can I return an anonymous struct in C?

前端 未结 7 644
青春惊慌失措
青春惊慌失措 2020-12-17 07:49

Trying some code, I realized that the following code compiles:

struct { int x, y; } foo(void) {
}

It se

7条回答
  •  粉色の甜心
    2020-12-17 08:37

    This works up to the newest version of GCC. It is particularly useful for creating dynamic arrays with macros. For instance:

    #define ARRAY_DECL(name, type) struct { int count; type *array; } name
    

    Then you can make the array with realloc, etc. This is useful because then you can create a dynamic array with any type, and there is one way to make all of them. Otherwise, you would end up using a lot of void *'s and then writing functions to actually get the values back out with casts and such. You can shortcut all of this with macros; that is their beauty.

提交回复
热议问题