How can I return an anonymous struct in C?

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

    Here's a way to return anonymous structs in C++14 without any hacks I just discovered.
    (C++ 11 should be sufficient, I suppose)
    In my case a function intersect() returns std::pair which is not very descriptive so I decided to make a custom type for the result.
    I could have made a separate struct but it wasn't worth since I would need it only for this special case; that's why I used an anonymous struct.

    auto intersect(...params...) {
        struct
        {
            Point point;
            bool intersects = false;
        } result;
    
        // do stuff...
    
        return result;
    }
    

    And now, instead of the ugly

    if (intersection_result.first) {
        Point p = intersection_result.second
    

    I can use the much better looking:

    if (intersection_result.intersects) {
        Point p = intersection_result.point;
    

提交回复
热议问题