Weird C program
Check the followin开发者_运维问答g code snippet
struct st
{
struct st
{
int a ;
int b ;
} st;
int a1 ;
} ;
struct st obj ;
struct st obj1 ;
int main()
{
return obj.a1 + obj1.b ;
}
Microsoft's compiler Visual Studio 6.0 compiles the program succesfully. I am confused with the use of 'struct st'. What is the size of obj and obj1?
GCC gives
error: nested redefinition of ‘struct st’
error: ‘struct st’ has no member named ‘a1’
If VC6 compiles this, that's fine, but this is invalid.
If you want to know the size of obj, that's sizeof obj
. I'd assume VC6 just flattened out the structure and assigned it three ints.
The size of obj and obj1 are the same. The value of obj.a1 + obj1.b is undefined, since neither was initialized AND your code AND compiler are broken. If that actually BUILT, all bets are off.
NB:
That code got A LOT of 'help' from its compiler to actually work. By 'help' I mean "We have a deadline to push this out ... its bug triage time, especially where the parser is concerned!"
Just having a quick glance at this makes me think that you have had defined one struct, declared two variables of type struct. Hence sizeof(obj) and sizeof(obj1) should be the same since they both are of type st! Needless to say, nested structs with same name is illegal! And surprised that it compiled. But remember, C has changed since VC 6 was out (if my memory serves me correct).
This is not a valid C code. There's no "class scope" in C and from the point of view of C language, both definitions of struct st
define the same type twice. This is illegal.
This is only well-formed as C++ code, but other than that the program simply calculates and returns 0. Why it jumps through all these hoops to return a 0 is beyond me. The program is ill-formed as C++ as well. It is illegal to declare class st
as a member of class st
(i.e. with the same name).
精彩评论