Functions

• 11-25-2006
Kevineze
Functions
Im C++ newbie im started understanding if commands,loops, and strings and even made a mini project by maiking a basic math quiz. the thing i wanna hit next is understandign functions. the tutorial is too plain can ne1 give a better example of when and how to use functions and explain it?
• 11-25-2006
manutd
Let me show you, say, a function that squares it's input:
Code:

```long square (long x) {     return x*x; }```
This function takes one argument, which is named x and is of type long:
Code:

`long square (long x)`
It also returns a long:
Code:

`long square (long x)`
This is the line that returns the value:
Code:

`return x*x;`
That's it! While this is a highly simplified example, it illustrates the basic concepts of functions.
• 11-25-2006
Kevineze
thanks
• 11-25-2006
Kevineze
but how would you use that square function in a program i tryed but got confused by ho to declare x
• 11-25-2006
manutd
Sorry. Look at this:
Code:

```long thenum = 3;    //This is our number. thenum = square(thenum);    //This gets an argument of thenum and returns it's result into thenum.```
• 11-25-2006
Kevineze
Ok that explains it better but at the top I have to declare the function like int ( x and whatever
how would I declare the function by using only one variable?
• 11-25-2006
Kevineze
so fricking confusedy if im being a pain
Code:

```#include <iostream> using namespace std; int square x; int main() {   int x;       cout<<"Please input the number to be squared: ";   cin>> x ;   cin.ignore();   cout<<"The square is  <<"\n";   cin.get(); } long square (long x) {     square x*x; }```
I know this is completely wrong but this is my futile attempt to apply what you just told me into a program. can u tell me wat i did wrong?
• 11-25-2006
CornedBee
Just about everything. What you need is a good introductory book. See the sticky thread.
• 11-25-2006
swgh
>int square x;

I think you meant that to be a function prototype. What you have done is created a
global variable.

>cin.ignore();

You do not need that in there at all

You need to pass the argument the function for it to calculate the result.

Code:

`square ( x );`
Oh, and you declared the prototype ( global variable ) of type int, when the function
square is defined as long. A function header and a function prototype must match in return types apart from function overloading - which is a different matter all togther. There are a few more errors too.

As cornbee said, it is best you read a tutorial or get a good beginners book. Check out the book recomendations on this site for some advise on what one(s) to get.
• 11-25-2006
manutd
Read my posts (and forward declare as long square (long x);)