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
1.5k views
in Technique[技术] by (71.8m points)

c++ - Semicolon after class declaration braces

In C++ classes, why the semi-colon after the closing brace? I regularly forget it and get compiler errors, and hence lost time. Seems somewhat superfluous to me, which is unlikely to be the case. Do people really do things like:

class MyClass
{
.
.
.
} MyInstance;

I get it from a C compatibility point of view for structs and enums, but since classes aren't part of the C language I guess it's primarily there the keep consistency between similar declaration constructs.

What I was looking for was more related to design rationale rather than being able to change anything, although a good code completion IDE might trap this before compilation.

See Question&Answers more detail:os

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

1 Answer

0 votes
by (71.8m points)

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 */
} 

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

2.1m questions

2.1m answers

60 comments

57.0k users

...