简体   繁体   中英

Difference between }; and } in C++

brand new to C++.

Woking on a project for an assignment, and in some example code I have found methods ending with }; instead of the typical (expected) }

For example:

CircBuffer::CircBuffer()
{
    cout<<"constructor called\n";
    cout<<"Buffer has " << BufferSize << "elements\n";

    for (int i = 0; i<= BufferSize -1; i++)
    {
        Buffer[i] = 0;
    }

    ReadIn = WriteIn = 0;
    setDelay(0);

}; // <=== HERE

I can't find any information as to why this would be done online.

Thanks, Lewis

That trailing ; in namespace scope constitutes an empty declaration . What you have in the above code is seen by the compiler as

CircBuffer::CircBuffer()
{
  ...
}      // <- the `CircBuffer::CircBuffer` definition ends here

;      // <- an empty declaration that declares nothing

Ie the method definition does not really end with }; from the compiler's point of view. It ends with } , and the ; is treated completely separately and independently.

Empty declaration was illegal in the original version of C++ and in C++03, but it was legalized in C++11. The code you quoted above is therefore invalid in C++98 and C++03, but legal in C++11. However, even C++98 compilers often supported empty declarations as a non-standard extension.

Note that the above applies only to out-of-class function definitions (as in your example). With in-class member function definitions the trailing ; has always been legal (and optional)

class C
{
  C()
  {
    ...
  }; // <- ';' not required, but legal even in C++98
};

(In this case the optional ; is actually a part of member definition, meaning that the definition does indeed end in }; and does not introduce an empty declaration.)

When you see something like that in the actual code, it is probably just a bad habit, maybe based on the confusion between the in-class and out-of-class definition contexts.

Could be for consistency or it could be a reminiscent of old code, for example if the original was just a declaration:

CircBuffer::CircBuffer();

and someone wanted to add an inline implementation, he might have clicked before the trailing ; and started writing the body there, forgetting to remove the ; .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM