Difference between }; and} in C ++
new to C ++.
Woking in the project for assignment, and in some sample code I found methods ending in}; instead of the usual (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 cannot find any information on why this would be done online.
Thanks Lewis
source to share
That trailing ;
in the namespace scope is 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
those. the method definition doesn't really end from the };
compiler's point of view. It ends with }
, but is ;
processed completely separately and independently.
Blank declaration was illegal in the original C ++ and in C ++ 03, but it was legalized in C ++ 11. So the above code is not valid in C ++ 98 and C ++ 03, but is legal in C ++ 11. However, even C ++ 98 compilers often supported empty declarations as a non-standard extension.
Note that the above only applies to definitions outside of the class (as in your example). With class member function definitions at the end was ;
always legal (and optional)
class C
{
C()
{
...
}; // <- ';' not required, but legal even in C++98
};
(In this case, the optional ;
is actually part of the member definition, which means the definition does indeed end with };
and does not introduce an empty declaration.)
When you see something like this in actual code, it is probably just a bad habit, possibly based on confusion between class definition and outside of class contexts.
source to share
It could be for consistency, or it could resemble old code, for example if the original was just a declaration:
CircBuffer::CircBuffer();
and someone wanted to add an inline implementation, he might have pushed before the trailing ;
and started writing the body there, forgetting to delete ;
.
source to share