175

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?

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Logan
  • 1,629
  • 2
  • 7
  • 6
  • 42
    A definition is also a declaration. But I would say your answer was correct. –  Feb 20 '19 at 16:16
  • 218
    It's a tricky nitpicking question and has no bearing on anyone's ability to program well. – phonetagger Feb 20 '19 at 16:18
  • 3
    if you read "declaration" as "declaration without definition" then the answer is false, though yours is a valid interpretation imho – 463035818_is_not_an_ai Feb 20 '19 at 16:18
  • 1
    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. – mcabreb Feb 20 '19 at 16:20
  • 41
    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."? :/ – Algirdas Preidžius Feb 20 '19 at 16:20
  • 19
    @phonetagger All this confusion goes to show how badly worded the question is. – François Andrieux Feb 20 '19 at 16:20
  • 4
    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. – einpoklum Feb 20 '19 at 16:21
  • 34
    [Hanlon's Razor](https://en.wikipedia.org/wiki/Hanlon%27s_razor) suggests that the author of the test mixed up "declaration" and "definition". – Sneftel Feb 20 '19 at 16:21
  • 4
    Just run away from this test any other tests this provider offers. – SergeyA Feb 20 '19 at 16:34
  • 10
    Clear, unambiguous language is vitally important to programming. This teaches the wrong lesson. – user4581301 Feb 20 '19 at 16:42
  • 6
    `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. – Barmar Feb 20 '19 at 20:46
  • 2
    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. – jamesqf Feb 20 '19 at 22:32
  • The grammar in the standard indicates that any terminating semicolon is *part of* the declaration. – Eric M Schmidt Feb 21 '19 at 06:41
  • 1
    isn't the `int func();` rather named a prototype? – prout Feb 21 '19 at 07:15
  • 1
    @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. – hyde Feb 21 '19 at 07:54
  • 2
    @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. – David R Tribble Feb 21 '19 at 16:56
  • 1
    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. – Leo Heinsaar Feb 21 '19 at 18:15
  • 2
    If you want to do anything even remotely useful, you'll need many semicolons somewhere after your function declaration. – wrtlprnft Feb 22 '19 at 05:49
  • 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. – Justin Time - Reinstate Monica Feb 22 '19 at 18:44
  • 5
    How to make people feel worse about their programming ability: ask trick questions and expect a specific answer. – Ian MacDonald Feb 24 '19 at 13:48
  • 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! – Jay Speidell Feb 26 '19 at 01:23
  • 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... – ANone Feb 22 '19 at 12:05
  • How about `#define X ;` then `int foo() X`? Is that considered "a semicolon"? – L. F. Mar 23 '19 at 05:23

12 Answers12

163

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.

Sneftel
  • 40,271
  • 12
  • 71
  • 104
jwismar
  • 12,164
  • 3
  • 32
  • 44
  • 10
    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. – I Funball Feb 21 '19 at 18:55
  • 16
    @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. – Peter - Reinstate Monica Feb 22 '19 at 14:44
  • 6
    @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. – Lightness Races in Orbit Feb 23 '19 at 13:23
  • 2
    Any exam question that's unclear to someone who knows the content being tested for is bugged. – Nat Feb 25 '19 at 20:47
  • 2
    Sounds like we need to add an undefined behavior clause to the English language – Nick Mertin Feb 26 '19 at 19:52
148

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

Arne Vogel
  • 6,346
  • 2
  • 18
  • 31
  • 2
    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. – supercat Feb 21 '19 at 18:41
  • 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. – David Hammen Feb 23 '19 at 22:23
  • 1
    @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*. – Peter Cordes Feb 24 '19 at 02:14
85

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

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Eric Lippert
  • 647,829
  • 179
  • 1,238
  • 2,067
  • Comments are not for extended discussion; this conversation has been [moved to chat](https://chat.stackoverflow.com/rooms/188924/discussion-on-answer-by-eric-lippert-isnt-a-semicolon-needed-after-a-func). – Samuel Liew Feb 23 '19 at 14:28
25

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.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Luca Corsini
  • 738
  • 4
  • 20
  • 3
    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 – Luca Corsini Feb 20 '19 at 16:27
  • 11
    Absolutely. Honestly, I learned more about function declaration-definition from getting the question wrong than I would've had I gotten in it correct. – Logan Feb 20 '19 at 16:35
  • 1
    @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 Feb 20 '19 at 19:17
  • 2
    ... 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. – bolov Feb 20 '19 at 19:17
20

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.

Marc van Leeuwen
  • 3,605
  • 23
  • 38
  • 1
    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. – Marc van Leeuwen Feb 22 '19 at 14:35
  • 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*. ;) – Quuxplusone Feb 23 '19 at 06:40
  • @Quuxplusone if the compiler rejects your program, your program doesn't have any function declarations in it :) – Ben Millwood Feb 24 '19 at 06:04
6

This depends on whether we are declaring or defining the function. If we are declaring the the function, we need to include the semicolon (;), and if we are defining the function, the semicolon is not needed.

A declaration is like this:

int add(int, int);

And a definition is like this:

int add(int a, int b)
{
    // ...
}
L. F.
  • 19,445
  • 8
  • 48
  • 82
  • 10
    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. – MSalters Feb 21 '19 at 08:22
6

It's a pity the question that you took doesn't say "directly after". We could for example write this:

int func()  /* My function */ ;

Or I could write:

int func()
int a = 42;

In the first case the semicolon is not directly after the declaration, but that would be OK.

In the second case there is a semicolon "after" the declaration, but not directly after.

I think Eric Lippert has the right idea in his answer.

It's like saying "should there be a period after the end of a sentence in English?". Arguably, a sentence already has a period at the end (otherwise it wouldn't be a sentence) and therefore there should not be a period after the sentence..

Nick Gammon
  • 1,173
  • 10
  • 22
  • 4
    Nice. Ending that sentence with an extra period. I see what you did there. – David S Feb 22 '19 at 13:43
  • 2
    `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 Feb 22 '19 at 19:32
  • 1
    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. – Nick Gammon Feb 22 '19 at 19:44
  • 1
    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 Feb 25 '19 at 22:56
  • ... (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! – Eric Lippert Feb 25 '19 at 22:58
6

Even though I agree with almost all of the other answers, stating that the question is worded very ambiguous, and that your answer is technically correct, allow me to give a different perspective:

This is how I've always called them:

void func();  // The function prototype

...

void func()
{
    // The function definition
}

I'm assuming the question was made up with this terminology in mind.

Definition and declaration are both the same concept in my eyes. "I define x = y" == "I declare x = y".

But of course, there's a big difference between the function prototype (on top) and the actual definition of the function.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Opifex
  • 362
  • 4
  • 15
  • 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 Feb 22 '19 at 13:41
  • 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." – Opifex Feb 22 '19 at 15:56
  • @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.) – Peter Cordes Feb 22 '19 at 19:36
  • 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. – David S Feb 26 '19 at 10:13
4

You can use ; for prototypes only.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
M7off
  • 137
  • 1
  • 9
4

It's kind of a tricky question, but they used the word declaration which means something like this:

int example();

So it's true in this case.

If they'd used the word implementation then it'd been false.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
2

Semicolon (;) is used to tell the compiler that after this semicolon (;) a new statement starts.

So I think the semicolon (;) is required during a function declaration only. So according to me, the answer will be true.

Jatinder
  • 96
  • 2
  • 11
  • Declarations are not statements though. – HolyBlackCat Mar 24 '19 at 08:01
  • 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). – Jatinder Mar 25 '19 at 10:27
2

When functions are defined before main():

  • Don't need semicolon because the function is already defined

When functions are defined after main():

  • Need semicolon because because you are prototyping that function and telling the compiler that the function exits.
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
shiv shah
  • 77
  • 8