Isn't a semicolon (';') needed after a function declaration in C++?

21,304

Solution 1

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.

Solution 2

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;.)

Solution 3

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. :-)

Solution 4

You can declare a function like this too:

int func(){
    return 1;
}

The statement is very ambiguous. The right answer should be: it depends on how you declare the function.

Anyway, I'd have chosen false too, and maybe you can report the question to someone.

Solution 5

A semicolon (';') is not needed after a function declaration.

True or False.

True. A semicolon is not needed after any declaration. Nor after any definition. Nor after any statement.

Many kinds of declaration have to end with a semicolon, as the syntax in section 7 [dcl.dcl] specifies. But there is never any need to write a second one after that.

Share:
21,304

Related videos on Youtube

Logan
Author by

Logan

Updated on April 25, 2020

Comments

  • Logan
    Logan about 4 years

    I just recently took an intermediate programming test, and one of the questions I got wrong was as follows:

    A semicolon (';') is not needed after a function declaration.

    True or False.

    I chose "false" (and please correct me if I'm wrong because I feel like I'm going crazy), a function declaration is what you write before the definition (at the top of the code) so the compiler knows the function call before even calling it, and a function definition is what makes up the function as a whole.

    I.e.,

    Declaration:

    int func();
    

    Definition:

    int func() {
      return 1;
    }
    

    Shouldn't the answer to this be false?

    • Admin
      Admin about 5 years
      A definition is also a declaration. But I would say your answer was correct.
    • phonetagger
      phonetagger about 5 years
      It's a tricky nitpicking question and has no bearing on anyone's ability to program well.
    • 463035818_is_not_a_number
      463035818_is_not_a_number about 5 years
      if you read "declaration" as "declaration without definition" then the answer is false, though yours is a valid interpretation imho
    • mcabreb
      mcabreb about 5 years
      I think you are correct, but it maybe they wanted it to be a tricky question. You should ask for the reasoning behind the answer given as valid.
    • Algirdas Preidžius
      Algirdas Preidžius about 5 years
      I always find the questions, that result in double-negatives, confusing. In my mind, such questions are designed to trip students up. Why couldn't the question be formed in a following way: "A semicolon (';') is always needed after a function declaration. True or False."? :/
    • François Andrieux
      François Andrieux about 5 years
      @phonetagger All this confusion goes to show how badly worded the question is.
    • einpoklum
      einpoklum about 5 years
      As @phonetagger suggests, this question should not be on an "intermediate programming test", it is super-nitpicky and confused people easily, like it confused you. Don't go crazy! It's not really your fault if you didn't mark the answer they expected.
    • Sneftel
      Sneftel about 5 years
      Hanlon's Razor suggests that the author of the test mixed up "declaration" and "definition".
    • SergeyA
      SergeyA about 5 years
      Just run away from this test any other tests this provider offers.
    • user4581301
      user4581301 about 5 years
      Clear, unambiguous language is vitally important to programming. This teaches the wrong lesson.
    • Barmar
      Barmar about 5 years
      int func(float), var; declares a function and a variable. You need a semicolon after the entire statement, but not after the function declaration itself. But I doubt this is what the quiz author intended.
    • jamesqf
      jamesqf about 5 years
      And the bottom line is that knowing whether that particular line of code is called a declaration, a definition, or a whizbang does not matter to your ability to write code.
    • Eric M Schmidt
      Eric M Schmidt about 5 years
      The grammar in the standard indicates that any terminating semicolon is part of the declaration.
    • prout
      prout about 5 years
      isn't the int func(); rather named a prototype?
    • hyde
      hyde about 5 years
      @NeilButterworth I would say, function definition also declares it, but text "this line is function declaration" would in any normal context mean it is a forward declaration specifically, and not a definition, without ambiguity.
    • David R Tribble
      David R Tribble about 5 years
      @phonetagger hit the nail on the head. When I interview people, I don't care about syntactical minutia, but about how well they can program and how they think about solving problems.
    • Leo Heinsaar
      Leo Heinsaar about 5 years
      I stopped accepting those kinds of tests long ago — I would never want to work with a team selected by perfect passes of tests like that. I suggest you do the same — the sooner, the better. Join a team that has been selected by real-life approaches to real-life problems.
    • wrtlprnft
      wrtlprnft about 5 years
      If you want to do anything even remotely useful, you'll need many semicolons somewhere after your function declaration.
    • ANone
      ANone about 5 years
      There are so many silly ways to parse this question, like how far "after" still counts. Like so many questions there is no way of asking the question unambiguously, without rendering it completely impenetrable to the target audience. Once you understand the topic the questions aimed at beginners will always seem like "lies to children", because they are. If you are hurt by the test score, there might be something to the nit-picking. If not just sit back and feel smug that you have a good idea of where semi-colons need to be...
    • Justin Time - Reinstate Monica
      Justin Time - Reinstate Monica about 5 years
      If we want to play language-lawyer, then we can say that a function declaration must be followed by either a semicolon or a function body (in which case it is also a definition). Or we could look at how a declaration statement in general can contain multiple declarators, in which case a function declaration can also be followed with other function declarations and/or variable declarations (provided they all share a common "decl-specifier-seq"). I doubt cases like this are what the question is actually about, though.
    • Ian MacDonald
      Ian MacDonald about 5 years
      How to make people feel worse about their programming ability: ask trick questions and expect a specific answer.
    • Jay Speidell
      Jay Speidell about 5 years
      Every CS exam I take has a couple of these. It's infuriating because it devalues my education. Accept that you're going to get them wrong, let the professor have their jollies, and roll with it. GPA isn't that important after you graduate. If the programming test was for a job... RUN!
    • L. F.
      L. F. about 5 years
      How about #define X ; then int foo() X? Is that considered "a semicolon"?
  • Luca Corsini
    Luca Corsini about 5 years
    Anyway, don't put the thing on a personal level. The important thing is that you understood how a function declaration-definition works, so don't worry about it too much, just make sure that the question will be at least checked and go on
  • Logan
    Logan about 5 years
    Absolutely. Honestly, I learned more about function declaration-definition from getting the question wrong than I would've had I gotten in it correct.
  • bolov
    bolov about 5 years
    @Logan don't worry too much. If you know how to write and read a function that's all you need. I personally hate these kind of questions that 1. are not well defined 2. test your theoretical knowledge of the syntax. To me it's like muscle memory. When I write each digit goes effortlessly to the key it is supposed to go, but if you give me a test about what keys should a digit press I would be completely hopeless without a keyboard to physically do the action ...
  • bolov
    bolov about 5 years
    ... Writing common syntax (e.g. like a function) will become a second nature to you. And when you will mess it up because you just switched languages, well... intellisense and syntax highlighting make for quick and efficient solutions. Invest your time and energy in something more useful.
  • MSalters
    MSalters about 5 years
    The problem with this answer is that it suggests that definitions and declaration are mutually exclusive. In fact, every definition is a declaration; definitions are a subset of declarations.
  • supercat
    supercat about 5 years
    It's also possible to use a typedef to define a function type, and then make use of that to declare many functions at once, e.g. typedef int fooProc(int); fooProc a,b.c.d.e; I'm not sure why standard headers for floppy-drive-based compilers didn't do that back in the day, since I would think it would have allowed header files to be quite a lot smaller and thus faster to process.
  • I Funball
    I Funball about 5 years
    I'd argue that true isn't correct because of the reason you gave. If there are cases when a semicolon is needed, then it is false (or not true). True is the absolute to me, if there are clear cases when it is needed then you cannot say true.
  • David S
    David S about 5 years
    To me your prototype is the declaration based on how I learned (not saying you're wrong either though), but then I'd also expect a prototype to specify the number and type of arguments, or void, but I expect you omitted that for brevity.
  • David S
    David S about 5 years
    Nice. Ending that sentence with an extra period. I see what you did there.
  • Marc van Leeuwen
    Marc van Leeuwen about 5 years
    I see that Eric Lippert already argued this point. I guess all the upvotes made me overlook it. Feel free to cast your votes there.
  • Peter - Reinstate Monica
    Peter - Reinstate Monica about 5 years
    @IFunball Good argument. Stupid natual languages. The sentence "A semicolon (';') is not needed after a function declaration" can be read as "A semicolon (';') is not (ever) needed after a function declaration" or as "A semicolon (';') is not (always) needed after a function declaration". Whether to qualify the statement as true or false hinges on choosing an interpretation. Strictly spoken the question is unclear and hence has no clear answer.
  • Opifex
    Opifex about 5 years
    David S: Yes, ofcourse it would also contain the number and type of arguments, but I indeed omitted them for brevity (note that there are also no arguments in the actual function declaration). However, I don't really agree when you say the full function declaration is called the prototype. I quote Wikipedia: "a function prototype or function interface is a declaration of a function that specifies the function's name and type signature (arity, data types of parameters, and return type), but omits the function body."
  • Peter Cordes
    Peter Cordes about 5 years
    int func() int a=42; doesn't compile. You need a comma, not another int. See @Arne's answer posted over a day before this. The only new thing in this answer is the last paragraph, with the analogy to English sentences.
  • Peter Cordes
    Peter Cordes about 5 years
    @DavidS: In C++, function declarations are always prototypes (or definitions), and void func(); is exactly equivalent to void func(void);. This is very different from C, where void func(); doesn't tell the compiler anything about the args, and isn't the same thing as void func(void);. A later prototype or definition are a good idea, otherwise the caller has to apply the default arg promotions (e.g. float -> double, and narrow integer types to int. Same rules as for args to variadic functions.)
  • Nick Gammon
    Nick Gammon about 5 years
    I didn't say the second example compiled. I was pointing out that saying that a semicolon was needed "after" the declaration was ambiguous. My example had a semicolon after the declaration but it doesn't compile.
  • Quuxplusone
    Quuxplusone about 5 years
    Pretty much any question that asks, "X is always true: true or false?" is going to have the answer "false." Heck, there's no need to have a semicolon anywhere; the compiler may complain and refuse to compile your program, but that's hardly the end of the world; I wouldn't call it a fundamental need. ;)
  • Lightness Races in Orbit
    Lightness Races in Orbit about 5 years
    @IFunball It's because "declaration", with no further context and no statement that we're language lawyering, is commonly understood to mean "a non-defining declaration". The question was unfair.
  • Samuel Liew
    Samuel Liew about 5 years
    Comments are not for extended discussion; this conversation has been moved to chat.
  • David Hammen
    David Hammen about 5 years
    Also consider int f(int(&g)(),int(*h)()){return g()+h();} This has three function declarations, one of which is followed by an open curly brace, another by a comma, and a third by a close parenthesis.
  • Peter Cordes
    Peter Cordes about 5 years
    @DavidHammen: That doesn't strictly declare functions other than int f(stuff). Even in the scope of the function, g is an automatic variable of type reference to function, and h is a pointer to function.
  • Ben Millwood
    Ben Millwood about 5 years
    @Quuxplusone if the compiler rejects your program, your program doesn't have any function declarations in it :)
  • Nat
    Nat about 5 years
    Any exam question that's unclear to someone who knows the content being tested for is bugged.
  • Eric Lippert
    Eric Lippert about 5 years
    This same problem occurs in error messages; a favourite example from C# is "A params parameter must be the last parameter in a formal parameter list". Now, suppose instead I said "A frob must be the last gloob in a gloob list". Does this mean (1) Every gloob list have exactly one frob at the end, like every question has exactly one question mark at the end, (2) A gloob list can have any number of frobs, but if it has one or more frobs, the last item must be a frob, like an even number can have any number of 02468, but one of the must be the last, or...
  • Eric Lippert
    Eric Lippert about 5 years
    ... (3) a gloob list can have zero or one frobs, and if it has one, it comes at the end? If you don't know the context, I'd think that (1) is the most sensible explanation, but in the case of "params parameter", (3) is the correct explanation. Many informal descriptions of programming language elements have a property that my technical editor friends call "COIK" -- Clear Only If Known. If you do not already understand the material thoroughly, a description of it is useless to you, but if you already understand it thoroughly, you don't need the description!
  • David S
    David S about 5 years
    My apologies, I ended up here looking at something C related and didn't note the change of language. I won't delete my comment in the interests of clarity, but consider it retracted.
  • Nick Mertin
    Nick Mertin about 5 years
    Sounds like we need to add an undefined behavior clause to the English language
  • HolyBlackCat
    HolyBlackCat about 5 years
    Declarations are not statements though.
  • Jatinder
    Jatinder about 5 years
    but after the function declaration, we are executing a new line of code using compiler. so I think before executing a new line of code compiler have to know where the previous line of code ends only then a compiler can generate native code(i.e 0101).