understanding larger function

I typed some code dealing with the "larger function" straight from a c++ book into my compiler to try and decode it to understand it better. But, the compiler keeps giving me the error message "undefined reference to larger" and "undefined reference to compareThree" in the main fuction. Two questions. Why is the compiler giving me this error message and why is the larger function outside of the main?....first time I have seen anything outside of the function main! Thanks


#include <iostream>

using namespace std;

double larger(double x, double y);
double compareThree(double x, double y, double z);


int main()
{

double one, two;

cout<<"The larger of five and ten is " << larger(5,10) << endl; /*HERE*/

cout<<"Enter two numbers: ";
cin>>one >> two;
cout<< endl;

cout<< "The larger of " << one << " and " << two << " is " << larger(one, two);
cout<< endl; /*HERE*/

cout<<"The largest of 45.299, 45.31, and 444.2 is "
<<compareThree(45.299, 45.31, 444.2) << endl; /*AND HERE*/
return 0;


return 0;
}
These lines:

1
2
double larger(double x, double y);
double compareThree(double x, double y, double z);

are declaring two functions, just like how you declare variables.

After you declare them, you need to actually write them out. Since they are their own functions, they are placed outside of the main function.

You will need to place the actual code for the functions somewhere in your source code, such as after the main function.

If you wanted to, you could also place the code before the main function, in which case you do not need to declare the functions first.

So your code should look something like this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include <iostream>

using namespace std;

double larger(double x, double y);
double compareThree(double x, double y, double z);

int main()
{
	//stuff
}

double larger(double x, double y)
{
	//stuff
}

double compareThree(double x, double y, double z)
{
	//stuff
}

Remember that you will need to return a value from the functions. Read more about functions in the tutorial:
http://www.cplusplus.com/doc/tutorial/functions/
http://www.cplusplus.com/doc/tutorial/functions2/
Last edited on
Thanks fg109. Alright I understand that a little. I didn't realize "larger" was a function like "main". I thought the only two functions that one could write code in were void and main. The code worked out though. But, I've read that a compiler reads from top to bottom. How was I receiving an error message for the larger function inside "main" before it even got to the larger function right after "main"?


EDIT: I get it. Thanks again.
Last edited on
Topic archived. No new replies allowed.