Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
263 views
in Technique[技术] by (71.8m points)

c - Nested structures

The following code compiles on a C++ compiler.

#include <cstdio>
int main()
{
    struct xx
    {
        int x;
        struct yy
        {
            char s;
            struct xx *p;
        };
        struct yy *q;
    };
}

Would there be any difference in behavior while compiling with a C compiler?
i.e. would there be any compiler error?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The code in your post is obviously incomplete, just declarations, so it is hard to say anything conclusive.

On obvious difference is that in C++ the inner struct type will be a member of outer struct type, while in C language both struct types will be members of the same (enclosing) scope. (BTW, was it your intent to declare them locally in main?).

In other words, in C++ the code that follows would have to refer to the structs as xx and xx::yy, while in C they would be just xx and yy. This means that the further code would look different for C and C++ and if it will compile in C++, it wouldn't compile in C and vice versa.

Added: C language prohibits declaring struct types inside other structs without declaring a member of that type. So, you struct yy declaration is illegal in C and will produce compiler diagnostic message. If you wanted your code to become legal in both C and C++, you'd have to combine the struct yy declaration with some data member declaration. In your case that could be pointer q:

struct xx {
        int x;
        struct yy {
                char s;
                struct xx *p;
        } *q;
};

The above is legal in both C and C++ (taking into account the differences I explained earlier), but your original declaration is not legal in C.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...