1.7 — Forward declarations and definitions

Take a look at this seemingly innocent sample program called add.cpp:

You would expect this program to produce the result:

The sum of 3 and 4 is: 7

But in fact, it doesn’t compile at all! Visual Studio 2005 Express produces the following compile errors:

add.cpp(5) : error C3861: 'add': identifier not found
add.cpp(9) : error C2365: 'add' : redefinition; previous definition was 'formerly unknown identifier'

The reason this program doesn’t compile is because the compiler reads files sequentially. When the compiler reaches the function call to add() on line 5 of main(), it doesn’t know what add is, because we haven’t defined add() until line 9! That produces the first error (“identifier not found”).

When Visual Studio 2005 gets to the actual declaration of add() on line 9, it also complains about add being redefined. This is somewhat misleading, given that it wasn’t ever defined in the first place. Later versions of Visual Studio correctly omit this additional error message.

Despite the redundancy of the second error, it’s useful to note that it is fairly common for a single error to produce (often redundant) multiple compiler errors or warnings.

Rule: When addressing compile errors in your programs, always resolve the first error produced first.

To fix this problem, we need to address the fact that the compiler doesn’t know what add is. There are two common ways to address the issue.

Option 1: Reorder the function calls so add() is defined before main():

That way, by the time main() calls add(), the compiler will already know what add() is. Because this is such a simple program, this change is relatively easy to do. However, in a larger program, it can be tedious trying to figure out which functions call which other functions (and in what order) so they can be declared sequentially.

Furthermore, this option is not always possible. Let’s say we’re writing a program that has two functions A and B. If function A calls function B, and function B calls function A, then there’s no way to order the functions in a way that they will both be happy. If you define A first, the compiler will complain it doesn’t know what B is. If you define B first, the compiler will complain that it doesn’t know what A is.

Function prototypes and forward declaration of functions

Option 2: Use a forward declaration.

A forward declaration allows us to tell the compiler about the existence of an identifier before actually defining the identifier.

In the case of functions, this allows us to tell the compiler about the existence of a function before we define the function’s body. This way, when the compiler encounters a call to the function, it’ll understand that we’re making a function call, and can check to ensure we’re calling the function correctly, even if it doesn’t yet know how or where the function is defined.

To write a forward declaration for a function, we use a declaration statement called a function prototype. The function prototype consists of the function’s return type, name, parameters, but no function body (the part between the curly braces). And because the function prototype is a statement, it ends with a semicolon.

Here’s a function prototype for the add() function:

Now, here’s our original program that didn’t compile, using a function prototype as a forward declaration for function add():

Now when the compiler reaches add() in main, it will know what add() looks like (a function that takes two integer parameters and returns an integer), and it won’t complain.

It is worth noting that function prototypes do not need to specify the names of the parameters. In the above code, you can also forward declare your function like this:

However, we prefer to name our parameters, because it allows you to understand what the function parameters are just by looking at the prototype. Otherwise, you’ll have to locate the actual function definition.

Tip: You can easily create function prototypes by using copy/paste on your function declaration. Don’t forget the semicolon on the end.

Forgetting the function body

One question many new programmers have is: what happens if we forward declare a function but do not define it?

The answer is: it depends. If a forward declaration is made, but the function is never called, the program will compile and run fine. However, if a forward declaration is made, the function is called, but the program never defines the function, the program will compile okay, but the linker will complain that it can’t resolve the function call.

Consider the following program:

In this program, we forward declare add(), and we call add(), but we never define add() anywhere. When we try and compile this program, Visual Studio 2005 Express produces the following message:

add.obj : error LNK2001: unresolved external symbol "int __cdecl add(int,int)" (?add@@YAHHH@Z)
add.exe : fatal error LNK1120: 1 unresolved externals

As you can see, the program compiled okay, but it failed at the link stage because int add(int, int) was never defined.

Other types of forward declarations

Forward declarations are most often used with functions. However, forward declarations can also be used with other identifiers in C++, such as variables and user-defined types. Other types of identifiers (e.g. user-defined types) have a different syntax for forward declaration.

We’ll talk more about how to forward declare other types of identifiers in future lessons.

Declarations vs. definitions

In C++, you’ll often hear the words “declaration” and “definition” used. What do they mean? You now have enough of a framework to understand the difference between the two.

A definition actually implements or instantiates (causes memory to be allocated for) the identifier. Here are some examples of definitions:

You can only have one definition per identifier. A definition is needed to satisfy the linker.

A declaration is a statement that announces an identifier (variable or function name) and its type. Here are some examples of declarations:

A declaration is all that is needed to satisfy the compiler. This is why using a forward declaration is enough to keep the compiler happy. However, if you forget to include the definition for the identifier, the linker will complain.

You’ll note that “int x” appears in both categories. In C++, all definitions also serve as declarations. Since “int x” is a definition, it’s by default a declaration too. This is the case with most declarations.

However, there are a small subset of declarations that are not definitions, such as function prototypes. These are called pure declarations. Others types of pure declarations include forward declarations for variables, class declarations, and type declarations (you will encounter these in future lessons, but don’t need to worry about them now). You can have as many pure declarations for an identifier as you desire (although having more than one is typically redundant).


1) What’s the difference between a function prototype and a forward declaration?

2) Write the function prototype for this function:

3) For each of the following programs, state whether they fail to compile, fail to link, or compile and link. If you are not sure, try compiling them!




Quiz Answers
1) Show Solution

2) Show Solution

3) Show Solution

4) Show Solution

5) Show Solution

6) Show Solution

1.8 -- Programs with multiple files
1.6 -- Whitespace and basic formatting

156 comments to 1.7 — Forward declarations and definitions

  • Alex

    Hi Alex,
    You listed the following as a reason for forward declarations:

    "If function A calls function B, and function B calls function A, then there’s no way to order the functions in a way that they will both be happy. If you define A first, the compiler will complain it doesn’t know what B is. If you define B first, the compiler will complain that it doesn’t know what A is."

    However, how can two functions ever call each other without producing a continuous repeating cycle. For example:

    I’d be ever so grateful if you could provide me with an example where a cycle doesn’t form when two functions call each other. This would better my understanding.

    Many thanks Alex, this site has helped me massively.


    • Alex

      In short, the answer is that one or both of your functions can have code that prevents the other function from being called if some other condition is true.

      Here’s a short example with a single function that you can extrapolate to the two function case:

      We cover this in more detail in the lessons in chapter 7 talking about recursion.

  • Val

    The function call of add is on line 5…..not 6. And add is defined at line 9 not 10 -(3rd paragraph). First example.

    Great website !!! I’m really finding it useful and enjoying it.



  • My dear c++ Teacher,
    Please comment following program. It works fine.

    With regards and friendship.

    • Alex

      I’m not sure what you want me to comment on, other than to say this program is hard to read because the function definitions are on the same line as the function prototypes.

      • My dear c++ Teacher,
        Please let me ask a clarification:
        Do you mean: main, f1, and f2, bodies are on the same line as the their types, names and parameters?
        My understanding is that f1 and f2 prototypes are above main() function, and their definitions below it.

        • Alex

          I mean the function bodies are on the same line as the function prototype. E.g. this:

          Instead of this:

  • My dear c++ Teacher,
    Please let me again ask you:
    Is it correct that "function prototype is a forward declaration for a function"?
    With regards and friendship.

  • My dear c++ Teacher,
    Please let me this question:
    In subsection "Declarations vs. definitions", 3rd paragraph, you state:
    "A declaration is a statement that defines an identifier (variable or function name) and its type.". Do you mean "… that declares an identifier …"?
    With regards and friendship.

    • Alex

      Poor wording on my part. I changed “defines” to “announces”. A declaration announces an identifier and its type. A definition instantiates or implements it.

  • My dear c++ Teacher,
    Please let me point out that in first paragraph you state:
    "The reason this program doesn’t compile is because the compiler reads files sequentially".
    Apparently you mean: "reads lines sequentially".
    Also in next sentence you state: "When the compiler reaches the function call to add() on line 6 of main(),".
    In PC I use, function call to add() is on line 5.
    With regards and friendship.

    • Alex

      It reads both files sequentially and the lines in the files sequentially. Your line numbers may vary slightly depending on whitespacing and whether you #include “stdafx.h” or not.

  • My dear c++ Teacher,
    Please let me point out that in "Function prototypes and forward declaration of functions" subsection, under program, you state:
    "Now when the compiler reaches add() in main, it will know what add() looks like (a function that takes two integer parameters and returns an integer), and it won’t complain."
    When compiler reaches add(), in main(), not only will know what add() looks like, but also will execute it, although it is AFTER main().
    With regards and friendship.

    • Alex

      No, that isn’t quite right. Remember, the compiler just does syntax checking -- the function isn’t actually executed until runtime.

      • My dear c++ Teacher,
        Please let me say that I am forced to use compilers online that compile, link, and run, altogether, by one click. One exception is
        that compiles (and apparently links) by clicking on "Compile", and executes by clicking on "Execute".
        With regards and friendship.

  • nopenope

    Maybe u should provide code tags for the second solution.

  • Kaleb

    You can tell the time and effort they put into this tutorial is outstanding! Great job, and very helpful 🙂

  • Richard

    I’m a bit confused about the relation between the terms “variable definition” and “variable instantiation”.

    Is my understanding of "definition" correct?
    "Definition is a more general term covering both the implementation (of a function for example) and the instantiation (which actually allocates some memory) of the identifier"

    • Alex

      A definition is a general term for the code that uniquely specifies how an identifier is implemented. It’s what the linker needs to work.

      For variables a definition causes an instantiation. For functions and types, the definition causes those things to become callable/usable.

  • Amryt

    #include <iostream>
    using namespace std;

    int add(int x, int y);

    int main()
        int a , b;
         cin>> a >> b >> endl;

        return 0;
    int add(int x , int y)
        return x+y;

    I tried adding cin fucntion so that ,  a value can be added at the output itself. why isn’t it working?
    what is wrong with the prog?

    Usind Dev c++

  • sabrina

    ""Now, here’s our original program that didn’t compile, using a function prototype as a forward declaration for function add():

    #include <iostream>

    int add(int x, int y); // forward declaration of add() (using a function prototype)

    int main()
        using namespace std;
        cout << "The sum of 3 and 4 is: " << add(3, 4) << endl; // this works because we forward declared add() above
        return 0;

    int add(int x, int y) // even though the body of add() isn’t defined until here
        return x + y;

    I used the same example, but they give me an error in "int main()" and they say that it is undefined. I am confused !!!

  • Harry

    "It is worth noting that function", "noting" should be "nothing". 🙂

    • Alex

      No, it’s correct as written. Noting as in “taking a note”.

    • Darren

      "It is worth nothing that function" cried Father. "I raised him from a babe, tried to teach him right from wrong, pass-by-const-reference rather than by-value, gave him a blueprint, a prototype to work form, and what does he give me in return? Nothing"

      (I think I’ve had too much coffee … and sugar)

  • Nyap

    So basically:
    - A definition makes the identifier (so in the case of a variable named x, it would be instantiated)
    - A decleration just says what an identifier is (so it would say that x is a variable) (and a function prototype is a decleration because it says that there is a function called x but it doesn’t actually make x)

    I got a bit confused so can you check if i’m correct 😛

    • Nyap

      Also, why do you call things like functions and variables "identifiers"? It’s like calling humans "names", it doesn’t make sense. Have I missed something in the lesson about naming identifiers?

      • Alex

        The term “identifier” in programming is basically synonymous with with the word “name” in common usage. So when we talk about identifiers, we’re talking about the names of things (functions, variables, etc…). We talk about naming variables and functions in one of the previous lessons.

        For example:

        i is the identifier (name) of this variable. When we talk about this variable specifically, we use “i”. When we talk about variable names generically, we use “identifier”.

    • Alex

      Yeah, that’s basically the right idea. Put another way, a declaration announces an identifier’s name and type so other code can reference it. A definition actually causes memory (for a variable) or code (for a function) to be created.

  • Trebor

    I think that the real answer to question 2 is

    int doMath(int first, int second, int third, int fourth)

    which is the function prototype. Another problem is that the title of Question 3 is at the end of Question 2.


  • Anderson

    Quiz answer 6. You say "The function call to add() matches the prototype […], the the implemented function also matches."

    The the that is redundant needs to go.

  • Lokesh

    Its interesting to see that the following code both compiles and links.
    (GCC 4.8.1 using `-std=c++11 -Wall -pedantic` as options)
    If I pass three arguments to add() in main() then the add() with three parameters is getting executed.
    Similar is the case with the print().
    I agree that having two functions with the same identifier in the same file is not a good idea.
    Depending on the number of parameters and return type, I think, the linker resolves the appropriate function.
    Anything that you want to add to it?
    Also, since redefinition is not allowed, how come it is not the case with add()?
    Are the two different add() functions treated as different functions?

    PS: Thanks for creating LearnCpp!
    Also I used backslash to escape the quotes within quotes in the code on lines 20 and 21 but the ‘code’ tags removed them. I can’t even write them here.

    • Alex

      Yes, what you’re experiencing is called “function overloading”. I talk more about this in lesson 7.6 -- Function overloading.

      In short, a function’s uniqueness is determined not only by its name, but also by the number and type of parameters (and a few other things, such as what class it’s in and whether it is const). This means you can have functions with the same name, so long as they have different numbers and/or types of parameters. In general, this is a good thing, particularly when we have functions that need to have different (but similar) behaviors based on the number or types of parameters.

  • @ALEX Your tutorial awesome but I am having a confusion b/w linking and compiling error…
    linking error will occur when there is a disparity between the number of data sent from main function and the number of params in the receiving function (or the prototype)& compiler error will occur when there is a disparity between the number of parameters in the fwd declaration and the function…A program runs sequentially so Question 3 and 4 and 5 are linking errors…Please correct me….

    • Alex

      A compiler error will occur when the compiler detects a syntax error, a naming collision, a mismatch in parameters, a call to an undefined function, etc…
      A linker error will occur when a function has been declared and called but not defined.

  • <<Really ,i like this site ,>>
    can anyone tell me that what is most important topic in c++?

    • Alex

      What is the most important part of a car?

      • Muhammad Kamal

        Everything. 😀
        And to Pradeep: Everything also lol. It’s all in harmony and actually depends on the type of problem you want a solution (program) for; if you wanna code a program that prints the sum of some numbers you input, then you don’t need to dive deep in the language… But if you’re making something heavy that reads values from a file or a block storage system or even from a network (I dunno if that’s even possible) then do hardcore operations including pointers and memory stuff (that I generally find hard :D) then you need a lot of knowledge. There’s no limit bro.

    • John Zulauf

      Most important? Write code every day.  As you learn you need to establish a clear, consistent mental model of how the various elements in C++ function and then write yourself small test programs to validate that model.  As you develop you need to develop the skills to create and debug solutions.  Writing code to solve new problems, and going through the process of framing the solution and identifying and resolving the issues with the solution.  As your project become more complex you’ll need to be able to assure their correctness.  Write code to test your components.  

      This is a craft, you have to practice it.

  • I am just learning this stuff and you guys are doing an awesome job. You have thrown in a term I haven’t seen yet… "linker". Normally when you list a new term you bold it and define it… not this time. Help me out?

  • Colin

    Just to say the site really is very helpful. Keep up the good work.

  • Ashley

    Hi, Alex. Great tutorial. Really enjoying it.

    Just one question about the declarations vs, definitions section above. Why in the first instance(definition) do you say with int x it "instantiates an integer variable named x", ie. memory is allocated for it, but in the second instance(declaration) you say "declares an integer variable named x". Didn’t you say at the start of the tutorial that when you write "int x" memory is allocated. So in other words in this case memory should be allocated in both instances and hence both are instantiated. Or did you just add them in both instances to show that int x can be a definition AND a declaration, and hence is initiated(memory allocated to it) in both cases? I read through the comments and actually saw that you replied to Matthew saying int x is both a declaration and definition. I just want to be sure that this was what you wanted to show in your above examples to start with.
    Thanks 🙂

    • Alex

      Yes, “int x” is both a declaration (telling the compiler that x is an integer variable) AND a definition (allocating memory for integer variable x).

      Later on, when we cover forward declarations of variables, you’ll learn it’s possible to declare variable x without instantiating it.

  • Iamthatis

    So essentially, a forward declaration behaves like a variable for a function whose definition has not yet sequentially appeared, (similarly to how X can be declared as a variable without being given a value) and the function prototype syntax distinguishes this "variable" as a function?

    • Alex

      Using the word variable is confusing here, because functions aren’t variables.

      A forward declaration simply allows us to tell the compiler that an object (a variable, a function, a type, etc…) exists but will be defined later. This allows us to use an object that may be defined later in the file, or perhaps in another file altogether.

      For functions, a forward declaration is done via a function prototype.

  • Unknown

    Can you all please help??
    when i saw the first question i couldn’t answer it because the question was :
    What’s the difference between a function prototype and a forward declaration?
    and when i saw the answer i saw "A function prototype can be used to forward declare a function" isn’t that mean that prototype is forward declaration or a type of it?
    please replay fast because i cant really continue if i didn’t understand something. and by the way thx alex for this awesome guide i really learned alot :).

    • Unknown

      and can you tell me please the Meaning of definition because i don’t understand how a function can be defined.

      • Alex

        A declaration tells the compiler that an identifier exists. A definition provides the compiler with enough information to instantiate or execute something.

        In the case of a function, a function declaration is just the prototype. It’s enough to tell the compiler that the function exists, but not enough to actually execute it. A function definition includes the prototype and the function body. A function definition is enough for the compiler to translate the function into machine language, so it can be executed.

    • Alex

      A function prototype declares a function’s name, return type, and parameters. It does not include the function body.

      A forward declaration tells the compiler that something exists before it is actually defined.

      For functions, a function prototype serves as a forward declaration.

      For other types of objects (e.g. user-defined types) they have a different syntax for doing forward declarations.

      Make sense?

  • Dan

    Hey Alex. Is there a way to tell the difference between a compiler-specific and linker-specific error in Microsoft Visual Studio Express 2013 for Windows Desktop?

  • Okay…compiler executes program sequentially but starts execution from top of main (). If execution starts from top of main(), compiler should know about add() (because it’s being called in main), but as written above, it doesn’t in this program:

    If add () is defined above main(), the program compiles fine. Does that mean compiler can’t jump below main () to find a function’s definition.  I know that’s stupid, but I proud myself for being stupid.

    • Alex

      Remember that the compiler compiles the program before execution can start. So for purpose of compiling a program, execution doesn’t matter.

      When the compiler compiles a file, it does so sequentially, from top to bottom. In your example, when it gets to the call for add(3,4), it checks its internal database to see if it’s seen a definition for add(3,4) and says, “nope!”. Then it gives you an error.

      There are a few ways to get around this:
      1) Define add() above main()
      2) Use a forward declaration, which tells the compiler “I promise I’ll define this later” (passing the buck to the linker)

      So basically, the compiler can’t jump below main() to find a function definition while compiling. This is an intentional limitation because the alternative (having the compiler look for a definition) would be both inefficient and complicated. Especially if add() used a definition the compiler hadn’t seen yet. In the worst case, that could exponentially increase your compile times.

  • begginner

    ohh yes .thankx i got it

  • begginner

    int add(int x, int y)
    int main(){

    return 0;
    why the output is  71 here?

    • Alex

      Similar answer to the above. 3+4 = 7, so that’s where the 7 comes from. Instead of calling function add(), you’re printing the memory address that function add lives at. Why this is printing a 1 I have no idea.

      In your code above, “add” should be “add(3,4)” or something.

  • apurva

    what is the difference between

  • Todd

    I’m loving these tutorials!
    I found a grammatical error - the first I have seen in all these tutorials!

    "A declaration is an statement"

    should be

    "A declaration is a statement"

    Also, "a integer" should be "an integer" in the code:

    Not trying to be annoying - just trying to keep your fantastic tutorials flawless!

  • techsavvy....aye

    #include <iostream>
    int add(int x, int y)
        return x + y;
    int main()
        using namespace std;
        cout << "The sum of 3 and 4 is: " << add<<
        (3, 4) << endl;
        return 0;

    when i type this program with     <<add<<
    like above why does it give an output of 14 instead of some error.
    if such a thing occurs in a large program how can it be resolved.How can i highlight the code the [/ ] brackets aren’t helping?

    • Alex

      It shouldn’t give an output of 14, it should give something like 010011724. cout << add will send the address of function add to cout, which prints "01001172" (or whatever address it is for you). (3,4) evaluates to 4, so it prints as 4.

      Generally if this were to occur in a large program, you'd note that the output was wrong and then find the line that was incorrect (possibly with the assistance of the debugger). Then you'd hopefully note that your statement should be cout << add(3,4) instead of cout << add << (3,4) and fix it.

  • kevin wiggins

    why is that variable declaration cause memory allocation and forward declaration does not for variables?

    • Alex

      Variable declarations are also variable definitions. We use these to tell the compiler that we need a variable to be allocated in memory at this point in the code.

      Forward declarations are pure declarations (not definitions), so no memory needs to be allocated for them. Forward declarations just let the compiler know that something exists. They don’t allocate memory for that thing.

  • Mark Knut

    You guys are the best! Keep up the great work and the updates!

  • Ponmani

    In your page 1.7 forward declaration, when you talked about declaration and definition,
    you gave examples as int x; for both declaration and definition?

    Is this correct? Declaration is something like x of type int exists and definition when memory comes in picture. Please elaborate author. Muchas Gracias in advance. Great tutorial.

    • Ponmani

      Actually I got it. Pure declarations and most definitions are declarations too! Sorry. I typed the comment premature and did not read the entire page.

  • Mayank

    I declared a function two times with same name,number of arguments, and data type but the compiler didn’t give an error.Why?

    • Alex

      Declaring an identifier more than once is not illegal. It’s just redundant.

      Note that you can only define your function once. If you try to define it more than once, your compiler will complain.

  • Jeydn Byrd

    There wouldn’t happen to be video tutorials, would there?

  • Karel

    Second question of the quiz in 1.7: "DoMath" should preferably and according to 1.4c be named "doMath"… Very nice tutorial and very understandable as well. Thanks so much Alex.

  • Daniel Ricci

    A function prototype is declaration statement that tells the compiler what a function’s return type is, what the name of the function is, and what the types of the function parameters are. A function prototype can be used to forward declare a function. A forward declaration tells the compiler about the existence of a function (or other type of object) in advance of where it is implemented.

    - I dont think there is a difference in terms of its usage.  Declaring a prototype is the act of forward declaring.

  • Catreece

    Handy information! A few things I was wondering about, though. And then I tested them because I realized I could answer my own questions. Huh. Well here's the answers in case anyone else is interested, then. =P

    #1: Does the int add(x, y) always have to be NAMED add(x, y)?

    I've tested and found I can call it addmoose(x, y) without issue.

    #2: Does the "add" part NEED to be part of it?

    moose(x, y) works just fine, apparently the "add" part is just there for good housekeeping and labeling.

    #3: can I have multiple functions named the same thing with different parameters?

    Yes and no I found out. I tried messing around with an add and a multiply function to test where the limits were, this is what I came up with:

    moose(x, y)
    moose(Na, Nb)

    Did not work. As far as it was concerned, the x/y and Na/Nb were identical; what they're called doesn't matter, only the number of parameters.

    moose(x, y)
    moose(Na, Nb, Nc)

    Did work. It doesn't seem to matter that you call it the same thing, so long as it can differentiate between moose(2 parameters) and moose(3 parameters). No, I don't know why I used moose.

    #4: Is it a good idea to name functions the same thing?

    Depends on the situation, I think. I guess if you're multiplying several different things, you could call several functions multiply and just alter the number of parameters. Since they're reusable in different contexts, and multiplying 3 parameters tends to work exactly the same no matter which parameter is being multiplied, so long as you have 3 of them, I suppose it's not that big of a deal.

    On the other hand, it's handy to name more complex functions to be clear about exactly what it is they're supposed to do. add(2 parameters) is pretty obvious that it adds two parameters together, so isn't exactly a big deal if you have add(x, y) and add(x, y, z).

    If you're trying something more complex, such as… pft, I dunno, something like "F = (D* (((E+Y)*(X/N)) *0.01) / (1+0.01* ((E+Y)*(X/N)))", then you might want to stick to a somewhat more descriptive title for the function. You COULD reuse totalNonsense(D, E, X, Y, N) with totalNonsense(X, Y, Z), but I wouldn't particularly suggest it due to issues of confusion.

    Anyway, just the random stuff I came up with when trying to figure out some exceptions to the rules. =3

    • Alex

      Regarding your point #3, C++ supports a concept called “function overloading”, whereby you can have multiple functions with the same name so long as no two functions have the same number of parameters of the same type in the same order. I tackle this topic in more detail in section 7.6 -- Function overloading.

      You’ll note the following does compile (we haven’t introduced double yet, but it’s a numeric data type like int):

      Regarding your point 4: as long as the use of the name is intuitive, there’s no problem using the same function name for more than one thing.

  • Ramakrishnan

    Hi Alex,

    Really, I am happy and admired about this tutorial. One of the best online tutorial I have ever seen. My question is do you have any idea about BODMAS Theorem. If you know can you please share with us ??

  • Matthew


    I don’t think

    is a definition.

    • Alex

      int x; is a definition (and a declaration). A definition defines how something is implemented -- in the case of variables, it’s probably more intuitive to say it instantiates the variable (causes memory to be allocated for it).

      One way to tell it’s a definition is to duplicate the line and see if the compiler complains (remember, things can only have one definition.

      If you do this:

      The compiler will complain.

      Although we haven’t covered it yet, it is possible to forward declare variables. In that case, the forward declaration is a declaration only (and does not allocate memory -- it just tells the compiler that a variable exists, but it’s defined elsewhere).

      I’ve updated the lesson text to be more clear about what definition means for variables.

  • amin

    you still don’t want to make a class for matlab or fortran?:)

  • Amjadb

    Can i just make a function call like : int add(int x, int y); before the line of add (3, 4) ?

  • fould12

    add.obj : error LNK2001: unresolved external symbol “int __cdecl add(int,int)” (?add@@YAHHH@Z)

    (?add@@YAHHH@Z) Makes me think of “add?…YAHHH!!”

  • Da-Rage44

    I have a stupid question, what does it actually mean by the program never defines the function?

    Do we assume we need a return value to define a function?

    • If you only make a forward declaration and never actually make the function the program never actually makes the function, meaning you will get errors when you’re trying to use the forward declaration.
      No you don’t need a return value to declare a function (void), it just needs to be declared somewhere (it doesn’t even need to have code in it).

    • Alex

      > what does it actually mean by the program never defines the function?

      It means the program doesn’t define a function body (the part of the function between the curly braces).

  • misserwell

    Thank you very much, the article is so clear , hope more and more visitor knows the web

  • donblas

    i know its been a while since this was used, but how do you make a program that does more than add a bunch of numbers?

  • Steven

    Love the tutorials,
    It says to declare a function you don’t need to define it. Then in the definition for function prototype it’s a “declaration of a function that includes the function’s name, parameters, and return type”

    But when I try to compile

    It tells me add() can’t take 2 arguments, and forces me to declare

    at the beginning before it will compile/work. Wouldn’t that be a declaration WITH a function prototype? or should

    work at the beginning and I’m doing something wrong.

    • Alex

      Your forward declaration of add has no parameters, but your definition of add has two. There’s a mismatch there that’s causing the problem. Fix the forward declaration so it has two parameters.

  • Anders Melen

    This tutorial is Perfect! Thank you so much for taking the time to help others learn a new great programming language! This could surly being published!, but thanks for making it available to all!

  • That was exactly what i needed ! Thank you for your support ! =)

  • StelStav

    Hi all,

    I would like to ask what is the reasoning of c++ creators for forward declaration? Why isn’t the compiler designed in such a manner so as to look for a function definition regardless of it being before or after the actual function calling?
    I would imagine that it is enough that the function definition resided in the same scope of the function call.
    Would the above (my) logic effect the efficiency of the executable or just the compilation?

    Thanks in advance

    very nice site btw, good job admins 🙂

    • Alex

      C++ was developed a long time ago when computers were slow and memory was expensive. I suspect this limitation was done for efficiency/simplicity, so the compiler doesn’t have to parse the file more than once, or maintain memory-intensive lookup tables for all function calls.

      More modern languages (like C#) allow you to declare functions in any order without forward declarations. It’s unfortunate that C++ hasn’t added this.

    • Darren

      Note that these beginner tutorials are using simple programs that are most conveniently written in just one source file. That means putting the function declaration in the source file with the main function. In "real world" programs function declarations will typically exist in header files so that they can be included by several source files possibly in a number of different programs. This is called programming by contract.

      For example, standard header files, such as <iostream>, define the standard routine library’s contract with the C++ programmer, promising you use of the functions and operators declared there in. All you need is the header file included in your source code; the linker will build the implementation details in to your code without you having to worry about those details. Without the declarations you would be forced to include the library implementations in your source code every time you wish to use one of the library functions. This would be tedious and cumbersome and programmers are inherently lazy, myself included.

  • tcp

    okay so sometimes when i get to

    int add(int x, int y);
    return x + y;

    the little dropdown-menu-checkbox doesn’t appear. why is this? the little alert box to the left of the code is green, so it’s not registering as a problem, but it refuses to run the program unless int add is a dropdown item. (the code is perfect, the only difference between the site’s code and my own is the dropdown box).

    the error message:

    error C2447: ‘{‘ : missing function header (old-style formal list?)

    • Auge

      Lets have a look at your code:

      The semicolon after the function header must be dropped:

      The error message tells you that the compiler doesn’t recognize to which function the part within the curly brackets belongs to.
      That’s also because of the semicolon after the function header.

  • Its very great tutorial , it’s helpful and very good.
    thank you for putting together this wonderful lessons.

  • Jeno


    Thanks for this wonderful website!!!

    I wrote the following code, it compiles, links and executes well, but it seems like the Return Value is wrong:

    The output return value I get is -6, but when I compute the numbers myself it is a wrong calculation.

    What Am I missing?

    • Michael B

      Order of Operations.

      PEMDAS is it?

    • Ireul

      Sorry for disrespectful comment, but you miss grade school math classes.

      7 + 8 - 3 * 7 = 15 - 21 = -6, the answer given by output is perfectly correct.

    • Liquidcool

      Rule 1: First perform any calculations inside parentheses.
      Rule 2: Next perform all multiplications and divisions, working from left to right.
      Rule 3: Lastly, perform all additions and subtractions, working from left to right.

  • Michael O.

    Hi Alex!

    Thanks a lot for these great tutorials, they’ve teached me a lot (I began 2 days ago).
    I agree with comment #1, these tutorials deserve a publication! I have tried to learn C++ some times before, but all the books I ended up with were hard to understand, the language was difficult, but these tutorials are very easy to understand, so again, thanks a lot Alex!

    -Michael O.

  • Florian


    I was thinking about it for a second, here is my explanation maybe someone can tell me if i am right.

    The program does work because c++ is compiled rather than interpreted. Which means as soon as we have created a prototyp the compiler gets through until the end and the compiled program has overwriten the first Prototype with the completed declaration (since the later declaration supersedes the first statement?


    • Eugene

      Not quite. The prototype does not get overwritten. Rather, the forward declaration informs the compiler of how a call of that function should look like, and thus the compiler can do the necessary setup and translate the function call into assembly/machine code.

      The function definition defines the code that will be executed when the function is called. In this case it is in the same source file as the function call, but it could be in a different source file, or might not even be available at all, e.g., just the object code is available in a shared library.

      That said, some functions whose function definitions are available might be inlined, i.e., the function call is replaced by the code of the function itself.

  • Florian

    i do have a problem understanding this:

    As the tutorial has stated earlier the program is running line by line so the function add would be unrecognized when it is called while add() is declared later on.

    On this example I would actually realize that we have created add() called it in main BUT we never reach the line where return x+y was written down.

    Basically I would expect a link error since the call ends up without returning anything?

    So my question is why does the program knows that add() returns the value x+y when it shouldn’t reach that declaration?

    Hope someone can understand this, i am German my English certainly lacks a bit.


  • Jon

    I don’t know if this was mentioned yet, on a brief scan I didn’t see it, so forgive me if you already answered this…
    You defined a function prototype as:

    A function prototype is a declaration of a function that includes the function’s name, parameters, and return type, but does not implement the function. In Question #2 on this page you give us:

    Did you mean us to solve for the forward declaration? If not, and you did mean to ask for the Function Prototype, shouldn’t you have given us only the Forward Declaration?

  • Prayrit

    This is a weird concept to me, because every other language I’ve worked with(java, c#, actionscript) doesn’t care where the function is located…

  • Danny

    Y doesn’t it work? =/ can someone please help

    • Furious Sideburns

      I’ll have a crack at answering this (I’m new to all this myself). If I’m understanding this right, you’ve got a few syntax errors.

      You’re missing a ” at the end of your first #include

      should be

      Also, you need to lose the ; on the end of your forward declaration and your add function


      should be


      • csvan

        You almost got it, however you NEED to have a ; at the end of forware declarations, since they are statements. Thus, it is compleely correct to write:

        but not without the semicolon. C++ statements are ALWAYS concluded with semicolon (except for some structures, such as while and for loops).

        Also, you CANNOT write a parameters name as a number (for example int add(int 1);), that is not allowed by the compiler.

        Keep on coding. Use it for good. 🙂

    • csvan

      You have 3 errors here:

      1. The first line is missing a closing quotation mark (“) at the end (it should be “stdafx.h”).

      2. The second include statement does not include anything. I think you meant to include iostream, therefore it should read:

      3. The name of a parameter (or any variable as far as I know) can never start with a number, or simply be a number. Therefore, you will have to rename the parameters both in the function prototype and definition for add, for example like this:

      and make the same changes to the body of the function (change 1 to a etc).

      Keep coding. Use it for good.

  • Justin

    Hi i have a question… i wrote my own code (same as yours but didn’t copy and paste) and i got a weird error that i do not under stand here is my code

    and this is the error message: 3 D:Dev-Cppmain.cpp expected `,’ or `;’ before ‘{‘ token


  • i m very weak in programing how can i improve it

    • Practice makes perfect! Pick a small project and figure out how to code it. Eg. a calculator, an address book, a little game, etc… You will learn as much from working on your own code and solving the problems you run into as you will from these tutorials.

      • csvan

        I double that. And triple it. I believe practical work is absolutely essential to building solid programming competence. You can learn all your life, but learning is in vain if it is only forgotten. Putting learnt knowledge into practice helps solidify it, and, I believe, can really contribute to it becoming a permanent part of your routine, not easily forgotten.

  • Julian

    I just found this site today after frustratingly leaving a different “learn C++” website, and I must say, your tutorials are a 100 times better than the other site I was on! 😛

    It had about one paragraph on functions which was badly worded, and then went on to something about arrays and loops and binary trees and it had examples but they used functions in a way I didn’t even know was possible and it just confused the crackers outta me.

    I like the way these tutorials don’t teach everything about ‘functions’ in the one chapter, they teach the aspects of functions that would be easy to understand at this point, and then explain the more advanced features when the reader has a bit more knowledge about C++.

    Thankyou! 😀

  • peddi

    Can we say the forward declaration in nothing but declaring the function globally, where as function prototyping is declaring function locally i.e, in the main function? is that only the difference? If then there is no way we can block the outsider from accessing our function which declared using forward declaration?

    • A forward declaration is a specific type of function prototype that allows you to declare a function before you actually define it. Unfortunately, there’s no way to “hide” such functions from “outsiders” -- even if you don’t declare a function prototype, someone who wanted to use your function could write a function prototype for it and then use it.

      The only way to hide functions is to put them inside classes, which we’ll cover much later in this tutorial.

  • adam

    in solution one it says eturn instead of return

    [ Fixed! Thanks. -Alex ]

  • adam

    So a function prototype is a kind of forward declaration?

    • It’s more accurate to say that one use of function prototypes is for forward declarations. Function prototypes can also be used in header files and in class declarations (covered in chapter 8). So function prototypes have more uses than just as forward declarations.

  • jeff

    i am experimenting the code from the quiz number 6 and i try to changed the forward declaration variables


    after that i compiled the code by using microsoft visual studio 2008 and i notice that the code is successfuly compiled and the program is smoothly running.

    why is it that the compiler is not complaining while the forward declaration variable is different from the implementation?

    • Good question! It turns out that the variable names in your forward declarations don’t have to match those in the actual definitions. This is because the variable names in the forward declarations simply aren’t used -- only the types are. You can even omit the variable names from the forward declaration altogether if you want.

      However, I think it’s generally good practice to put them in. If you see a forward declaration like this:

      It’s a lot less meaningful than if you see this:

  • This helped explain a lot of things I was previously having problems with.

  • Mitul

    /* I have writen one another Program like example 5*/

    #include <iostream.h>
    #include <conio.h>

    int add(int x, int y, int z);

    void main()
    int x,y,z;
    cout << "n Enter three number : n";
    cin >> x;
    cin >> y;
    cin >> z;
    cout << "n" << x << " + " << y << " + " << z << " = " << add(x, y, z) << endl;

    int add(int x, int y, int z)
    return x + y + z;

    • Doesn’t main have to be:


      so that main returns a value?

      • Many (most?) compilers let you get away with using void main() instead of int main(), and they will implicitly return 0 when you do this. However, it’s not technically part of the language, so I avoid it in my examples.

    • ice

      I tried to run your program and came up with and error like this
      1>---- Build started: Project: 1, Configuration: Debug Win32 ----
      1> 1.cpp
      1>c:\users\marius\documents\visual studio 2010\projects\1\1\1.cpp(2): fatal error C1083: Cannot open include file: ‘iostream.h’: No such file or directory
      ========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========

      • iLexy

        Since you use MSVS, you do not need to specify a library file, it takes care of that part for you so:

        #include <stdafx.h>
        #include <iostream>

  • Gary

    Hi there. I was wondering how come I have to type #include stdafx.h now. I haven’t used my compiler for a while, so I was just wondering. I can’t do this program unless I do it, but the Hello World one works just fine without it.

    By the way, in my older programs, the source files say “main.cpp” but the new one has 2 files, one that says stdfax.cpp and another one with the title of my project.

    I’m new to programming, so if my questions sound dumb, bear with me.

    • stdafx.cpp is a file that Microsoft compilers use to do precompiled headers (which makes you program compile faster), if you sent them up correctly. If you don’t want to deal with stdafx.h, you can always turn precompiled headers off (in the project settings).

    • Darren

      8 years later but still quite relevant.

      In more recent versions of Visual Studio there is an option to create an empty project which has the ‘pre-compiled headers’ option (plus some others) switched off by default. Unless specifically building an app for Windows I would recommend always starting a project as an "empty project"; you can always switch the various options back on at a later date.

  • Dan

    Ahh, ok… I’m getting a clearer picture of this now (re: my question a few days ago in the previous ‘functions’ section
    when I asked about the order of functions in Cpp code). This helps explain the reasons why it must be. 🙂

    Thanks Alex!

  • GovZ,

    Forward declarations are used only to tell the compiler about the existence of a function (or class or variable) before it is actually implemented.

    This information is only used during compile time. Consequently, forward declarations will not make your executables larger or slower.

  • GovZ

    Hello guys,

    You have a great tutorial here. Worthy of publication, IMHO.

    Anyways one question. Does Forward Declaration by function prototyping have an effect on the execution time or is this only used during the creation of some hash table or something? And that in the resulting executable, this step is not actually “re-read”.

    I hope I make sense. Thanks for your answers in advance. =)

Leave a Comment

Put C++ code inside [code][/code] tags to use the syntax highlighter