Isn't a semicolon (';') needed after a function declaration in C++?
You can have a situation where you declare and define the function in one step, i.e. if you include the function definition at the point where you're declaring it. So technically I suppose true is correct. But the question is worded in such a way that I would have answered it the way you did.
In addition to the "a definition is also a declaration" thing, the following is legal C++:
int f(), g();
This declares two functions,f
and g
, both without arguments and with a return type of int
, but the definition of f
is not followed (immediately) by a semicolon. Likewise, this is legal:
int f(), i = 42;
But it is indeed not allowed to omit the semicolon entirely in these cases, so it would be somewhat surprising if either was taken as an example of a declaration without a following semicolon. In fact, the following is illegal:
void *p, f() {}
Other than a (mere) function declaration, a function definition cannot be combined with any other declaration or definition to the same type-specifier. (If this were legal, it would define both a void *p
and a void f() {}
.)
In any case, this seems to be a "gotcha" type of question that should not be in an intermediate programming test.
(Oh, by the way, please don't actually write code like int f(), i = 42;
.)
The other answers and comments call out several of the many ways that this is a horrid, misleading and badly-written question. But there is another problem that no one else has identified yet. The question is:
A semicolon (';') is not needed after a function declaration. True or False.
OK, let's look at a function declaration:
int func(); /* */
/* ^ */
/* | */
/* That whitespace is "after the function declaration". */
That whole thing is the declaration. The declaration is not int func()
and then followed by a ;
. The declaration is int func();
and then is followed by whitespace.
So, the question is: is a semicolon needed after the declaration? Of course not. The declaration already has a semicolon in it which terminated it. A semicolon after the declaration would be pointless. By contrast, int func(); ;
would be a semicolon after a function declaration.
The question was almost certainly intended to ask the question "true or false: the last token in a function declaration is always a semicolon" But that's not the question that they wrote, because the author of the quiz was not thinking clearly about the problem.
My advice is to avoid programming language quizzes altogether. They're pretty awful.
Fun fact, while we are on the subject. In C#, these are all legal:
class C {}
class D {};
struct E {}
struct F {};
In C#, a class or struct declaration may end in a semicolon, or not, at your discretion. This odd little feature was added for the benefit of C/C++ programmers coming to C# who have it in their fingertips that type declarations end in a pointless semicolon; the design team didn't want to punish them for having this habit. :-)