Semicolon after class declaration braces
The semi-colon after the closing brace in a type declaration is required by the language. It's been that way since the earliest versions of C.
And yes, people do indeed do the declaration you just put up there. It's useful for creating scoped types inside of methods.
void Example() {
struct { int x; } s1;
s1.x = 42;
struct ADifferentType { int x; };
}
In this case, I think it's clear why the semi-colons are needed. As to why it's needed in the more general case of declaring in the header file I'm unsure. My guess is that it's historical and was done to make writing the compiler easier.
I guess it's because classes are declarations, even when they need braces for grouping. And yes, there's the historical argument that since in C you could do
struct
{
float x;
float y;
} point;
you should in C++ be able to do a similar thing, it makes sense for the class
declaration to behave in the same way.
The link provided by @MichaelHaren appears to provide the root cause. The semicolon (as others have pointed out) is inherited from C. But that doesn't explain why C used it in the first place. The discussion includes this gem of an example:
struct fred { int x; long y; };
main()
{
return 0;
}
Older versions of C had an implicit int return type from a function unless declared otherwise. If we omit the ;
at the end of the structure definition, we're not only defining a new type fred
, but also declaring that main()
will return an instance of fred
. I.e. the code would be parsed like this:
struct fred { int x; long y; } main()
{
return 0; /* invalid return type, expected fred type */
}