How can I return an anonymous struct in C?

前端 未结 7 648
青春惊慌失措
青春惊慌失措 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:27

    You probably cannot explicitly return some aggregate value from your function (unless you use a typeof extension to get the type of the result).

    The moral of the story is that even if you can declare a function returning an anonymous struct, you should practically never do that.

    Instead, name the struct and code:

    struct twoints_st { int x; int y; };
    struct twoints_st foo (void) {
       return ((struct twoints_st) {2, 3});
    };
    

    Notice that it is syntactically ok, but it is generally undefined behavior at execution to have a function without return (e.g., you could call exit inside it). But why would you want to code the following (probably legal)?

    struct { int xx; int yy; } bizarrefoo(void) { exit(EXIT_FAILURE); }
    

提交回复
热议问题