Disclaimer: This is not a technical, but a practical answer. See Other Technical Answers. This answer is stubborn and subjective, but please bear with me while I try to explain the big picture.
struct is a strange beast because the material you put between the closing bracket } and the semicolon ; , refers to content inside or in front of these brackets. I know why this is so, and grammatically it makes sense, but personally I find it very controversial, since curly braces usually mean an area:
Counterintuitive examples:
// declares a variable named `foo` of unnamed struct type. struct { int x, y; } foo; foo.x = 1; // declares a type named `Foo` of unnamed struct type struct { int x, y; } typedef Foo; Foo foo2; foo2.x = 2; // declares a type named `Baz` of the struct named `Bar` struct Bar { int x, y; } typedef Baz; // note the 'struct' keyword to actually use the type 'Bar' struct Bar bar; bar.x = 3; Baz baz; baz.x = 4;
There are so many subtle things that can go wrong with the dense syntax of struct and typedef , if used like that. As shown below, it is very easy to declare a variable instead of a type randomly. The compiler has limited help because almost all combinations are grammatically correct. They just don't necessarily mean what you're trying to express. This is a pit of despair .
Invalid examples:
// mixed up variable and type declaration struct foo { int x, y; } Foo; // declares a type 'foo' instead of a variable typedef struct Foo { int x, y; } foo; // useless typedef but compiles fine typedef struct Foo { int x, y; }; // compiler error typedef Foo struct { int x, y; };
For reasons of readability and maintenance, I prefer to declare everything separately and never put anything behind the closing brace. The cost of additional lines of code is easily outweighed by the intuitive syntax. I argue that this approach makes it easy to do the right thing and annoy doing the wrong thing .
Intuitive examples:
// declares a struct named 'TVector2' struct TVector2 { float x, y; }; // declares a type named 'Vector2' to get rid of the 'struct' keyword // note that I really never use 'TVector2' afterwards typedef struct TVector2 Vector2; Vector2 v, w; vx = 0; vy = 1;
LumpN Jun 15 '14 at 23:01 2014-06-15 23:01
source share