How can I return an anonymous struct in C?

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

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

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

It se

7条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-17 08:38

    This works in my version of GCC, but seems like a total hack. It is perhaps useful in auto-generated code where you don't want to deal with the additional complexity of generating unique structure tags, but I'm sort of stretching to come up with even that rationalization.

    struct { int x,y; }
    
    foo(void) {
       typeof(foo()) ret;
       ret.x = 1;
       ret.y = 10;
       return ret;
    }
    
    main()
    {
       typeof(foo()) A;
    
       A = foo();
    
       printf("%d %d\n", A.x, A.y);
    }
    

    Also, it's dependent on typeof() being present in the compiler -- GCC and LLVM seem to support it, but I'm sure many compilers do not.

提交回复
热议问题