Take a look at this seemingly innocent sample program called add.cpp:
#include <iostream>
int main()
{
using namespace std;
cout << "The sum of 3 and 4 is: " << add(3, 4) << endl;
return 0;
}
int add(int x, int y)
{
return x + y;
}
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(10) : error C3861: 'add': identifier not found add.cpp(15) : 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 it reaches the function call to add() inside of main(), it doesn’t know what add is, because we haven’t defined add() until later! That produces the error on line 10. Then when it gets to the actual declaration of add(), it complains about add being redefined (which seems slightly misleading, given that it wasn’t ever defined in the first place). Often times, a single error in your code will end up producing multiple warnings.
Rule: When addressing compile errors in your programs, always resolve the first error produced first.
In this case, that means we need to address the fact that the compiler doesn’t know what add is. There are three ways to fix this problem.
The first way is to reorder our function calls so add is defined before main:
#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;
}
That way, by the time main() calls add(), it will already know what add is. Because this is such a simple program, this change is relatively easy to do. However, in a large program, it would be extremely tedious trying to decipher which functions called which other functions so they could be declared in the correct order.
Furthermore, this option is not always available. 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.
Consequently, a better solution is to use a forward declaration. In a forward declaration, we declare (but do not define) our function in advance of where we use it, typically at the top of the file. This way, the compiler will understand what our function looks like when it encounters a call to it later. We do this by writing a declaration statement known as a function prototype. 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.
Here’s our original program with a forward declaration:
#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;
return 0;
}
int add(int x, int y)
{
return x + y;
}
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 could also forward declare your function like this:
int add(int, int);
However, we prefer the method where the parameters are named because it’s more descriptive to a human reader.
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:
#include "stdafx.h"
#include <iostream>
int add(int x, int y);
int main()
{
using namespace std;
cout << "The sum of 3 and 4 is: " << add(3, 4) << endl;
return 0;
}
In this program, we forward declare add(), and we call add(), but we never define add(). When we try and compile this program, Visual Studio 2005 Express produces the following message:
Compiling... add.cpp Linking... 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.
The third solution is to use a header file, which we will discuss shortly.
Quiz
1) What’s the difference between a function prototype and a forward declaration?
2) Write the function prototype for this function:
int DoMath(int first, int second, int third, int fourth)
{
return first + second * third / fourth;
}
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!
3)
#include <iostream>
int add(int x, int y);
int main()
{
using namespace std;
cout << "3 + 4 + 5 = " << add(3, 4, 5) << endl;
return 0;
}
int add(int x, int y)
{
return x + y;
}
4)
#include <iostream>
int add(int x, int y);
int main()
{
using namespace std;
cout << "3 + 4 + 5 = " << add(3, 4, 5) << endl;
return 0;
}
int add(int x, int y, int z)
{
return x + y + z;
}
5)
#include <iostream>
int add(int x, int y);
int main()
{
using namespace std;
cout << "3 + 4 + 5 = " << add(3, 4) << endl;
return 0;
}
int add(int x, int y, int z)
{
return x + y + z;
}
6)
#include <iostream>
int add(int x, int y, int z);
int main()
{
using namespace std;
cout << "3 + 4 + 5 = " << add(3, 4, 5) << endl;
return 0;
}
int add(int x, int y, int z)
{
return x + y + z;
}
Quiz Answers
1) Show Solution
1.8 — Programs with multiple files
|
Index
|
1.6 — Whitespace and basic formatting
|
1.8 — Programs with multiple files
Index
1.6 — Whitespace and basic formatting
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. =)
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.
rying out your second example i wrote:
#include
int add(int x+int y)
{
return x+y;
}
int main()
{
using namespace std;
cout
Please repost your question with the code embedded inside PRE html tags.
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!
-Dan
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).
/* 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;
clrscr();
cout << "n Enter three number : n";
cin >> x;
cin >> y;
cin >> z;
cout << "n" << x << " + " << y << " + " << z << " = " << add(x, y, z) << endl;
getch();
}
int add(int x, int y, int z)
{
return x + y + z;
}
Doesn’t main have to be:
not
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.
This helped explain a lot of things I was previously having problems with.
i am experimenting the code from the quiz number 6 and i try to changed the forward declaration variables
from
to
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:
now it’s clear and i understand well.
thank you very much!
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.
in solution one it says eturn instead of return
[ Fixed! Thanks. -Alex ]
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.
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! :P
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! :D
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.
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.
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
int add(int x,int y);
{
return x + y;
}
int main()
{
using namespace std;
cout << “the sum of 3+4 is : ” << add(3, 4)<< endl;
system (”pause”);
return 0;
}
and this is the error message: 3 D:Dev-Cppmain.cpp expected `,’ or `;’ before ‘{’ token
Thankz
Justin
You have a semicolon after the line declaring add:
should be:
#include “stdafx.h #include int add(int 1, int 2, int 3, int 4); int main() { using namespace std; cout << “The sum of first, second, third, and forth =” << add(1,2,3,4) << endl; return 0; } int add(int 1, int 2, int 3, int 4); { return 1 + 2 + 3 + 4; }Y doesn't it work? =/ can someone please help
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
and
should be
and
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. :)
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.
secure virginia slims ultra sunlight cigarettes
second-rate doral cigarette cheaply doral cigarette|penurious doral cigarettes
shoddy doral cigarettes cheap doral cigarettes
inferior gpc cigarette tuppenny gpc cigarettes
tuppenny gpc cigarettes cheap gpc cigarettes
discount doral cigarettes
Well lookie lookie! SPAM!! GTFO!!!!!
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…
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:
1.int DoMath(int first, int second, int third, int fourth) 2.{ 3. return first + second * third / fourth; 4.}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?
Hi,
i do have a problem understanding this:
#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; return 0; } int add(int x, int y) { return x + y; }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.
Thanks
Florian
Ok,
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?
Florian
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.
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.
Hi,
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:
// Preprocessor statement #include <iostream> //"Getem" Forward Declaration int Getem(int one, int two, int three, int four); //"Main" function declaration int main() { using namespace std; { std::cout<< Getem(7, 8, 3, 7)<<endl; } return 0; } int Getem(int one, int two, int three, int four) { return one + two - three * four; }The output return value I get is -6, but when I compute the numbers myself it is a wrong calculation.
What Am I missing?
Order of Operations.
PEMDAS is it?
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.
[url=http://drugpills.net/cialis.html][size=20][color=red][b]BILLIG CIALIS KAUFEN ONLINE[/b][/color][/size][/url]
[url=http://drugpills.net/cialis.html][img]http://drugpills.net/img/cialis1.gif[/img][/url]
[url=http://drugpills.net/cialis.html][size=20][b][color=blue]BILLIG CIALIS KAUFEN[/color]
[color=red]*** Jetzt Kaufen! ***[/color]
[color=green]CIALIS KAUFEN ONLINE[/color][/b][/size][/url]
[url=http://drugpills.net/cialis.html]Cialis Tadalafil Aus Indien
[/url]
[url=http://drugpills.net/cialis.html]Erektile Dysfunktion Cialis
[/url]
[url=http://drugpills.net/cialis.html]Besser Cialis Levitra Viagra, Die
[/url]
[url=http://drugpills.net/cialis.html]Kanada Cialis Online
[/url]
[url=http://drugpills.net/cialis.html]Cialis Dosis
[/url]
Cialis Gnc
Cialic Bestellen
Rabatt Cialis Levitra Viagra
Cialis Soft
Naturlichen Cialis
Cialis In Hohen Blutdruck Pressur
Cialis Droge Impotenz
Cialis Und Taub Bein
Wie Ist Cialis Zur Behandlung Von Herz-Probleme Bei Frauen
Viagra Cialis Und Drogen
Ist Die Bestellung Cialis Rechtlichen
Apotheken On Line Cialis
Billig Europaischen Cialis
Cialic Kaufen
Viagra Finden Suche 76k Cialis Websites Online Kostenlos Charles
Fakten Uber Cialis
Cialis Jeden Tag
Cialis Und Diabetes
Cialis Dreampharmaceuticals
Cialis Gelee
[i]Finden Cialis
Tadalafil Cialis Oder
Cialis Sales Uk
Verschreibungspflichtige Medikamente Viagra Cialis Propecia Mann Gesundheit
Cialis Tijuana
Generika Cialis Nexium Rabatt
Lilie Lcos Cialis
Cialis Kanada Rx
Cialis Frauen
Cialis Rx
Cialis Online-Verkauf
Indien Cialis
Rezept Fur Cialis Kaufen
Kaufen Viagra Cialis Levitra
Uprima Cialis Viagra
Besten Preis Auf Cialis
Medikamente Wie Viargra Und Cialis
Viagra Cialis Vs Foren
Ubernachtung Lieferung Cialis
Frei Cialis Ohne Rezept
[/i]
[u]Tadalis Edegra Generic Cialis
Kauf Cialis Online
Sie Cialis In Einer Apotheke
Kapsel Cialis
Kaufen Preiswerten Cialic
Viagra Cialis Vs
Online Cialis Traum Pharma -
Kaufen Besten K Cialis Gujpkr
Surfen Zu Kaufen Cialis Online-Link
Cialis Levitra Oder
Cialis V S Viagra
Softtabs Cialis
Cialis 20
Generic Cialis Uberprufung
Wirkstoff Cialis
Wie Kommen Sie An Kostenlose Proben Von Cialis
Cialis Rechtsanwalt
Caverta Cialis Billig
Cialis Maximalen Dosis
Schlagworter Avodart Cialis Clomid Diflucan Dostinex Glucophage
[/u]
[b]Online-Rezept Fur Cialis
Generic Cialis Tadalafil
Niedrigsten Preise Cialis
Cialis Patch
Cialic Ohne Rezept Bestellen
Cialis Erektion Gesundheit Mann Penis Viagra
Apotheke Cialis Silagra Cumwithuscom
Cialis Schuldenkonsolidierung
Viagra Edinburgh Seiten Suche Finden Kaufen Cialis
Avodart Cialis Clomid Diflucan Dostinex Gluco
Xanax Viagra Cialis Porn Rolex Gru?E Sturm Beta-Jahre
Cialis Cialis Forum Apotheke
Billige Marke Cialis
Cialis Ambien
Cialis, Wo
Flussigkeit Cialis Ordnungsgema?E Dosges
Cialis Und Viagra Forum
Keine Verschreibung Notwendig Cialis
Kostenlos Viagra Cialis Levitra Prozess Bietet
Cialis Genuinerx Net Viagra Viagra Viagra
[/b]