# Functions

## Recommended Posts

I have been having some trouble with functions, I can see how they will work, but maybe it's because I don't have my C++ lingo in check yet. Can someone explain in plain english how they work (I've already looked through books and tutorials).

##### Share on other sites
Do you wish to know how are they implemented at a lower level, or a more abstract explanation of what they can do and how to use them?

##### Share on other sites

A function is like a sub-recipie in a recipie book.

Medium Boiled eggs:
Take eggs, place in pot of boiling water.
Simmer for 5 minutes.
Remove from water, let cool.

Fancy Eggs:
Take your eggs, boil them medium.
Remove the shell of the egg.
Cut the egg in two.
Scoop out the yolk.
Blend the yolk into a paste.
Use a cake decorator to place the pasted yolk back into the egg.

...

Now notice how part of the "Fancy Eggs" was "boil them medium" -- this is the same as a "function call" -- run the "Medium Boiled Egg" function on the eggs, and take the result.

The more complicated the recipie, the more sub recipies you end up with. Sometimes you even reuse the sub recipie multiple times -- the same as calling the function multiple times.

##### Share on other sites
The above is a pretty good explanation of the idea behind functions in C++. Translating that to the language you get something like:

// This is the declaration of a function.std::string cookMediumEggs ( int numEggs ){    // Set the watertemperature    int waterTemp = 100;    // This is a function call. I call a function that puts the eggs in the water.    // The function returns a pointer to a "BoilingPot" object, which I can use in     // the rest of my code    BoilingPot* putEggsInWater ( waterTemp, numEggs );    if ( RemoveEggsFromPot ( BoilingPot ) == true )    {        std::string returnvalue = "Your eggs have been cooked!";    }    else    {        returnvalue = "Alas, your eggs weren't ready yet.";    }}// You can call this function simply by writing down its name and argument list. // If a function returns a value, you might want to store that value as well.// Example:char * result = cookMediumEggs(4);std::cout << result << std::endl;

Note, this code won't work since it calls to imaginary undefined functions, but it should give you an idea of how functions can work. Basically, a function is useful for 'wrapping' any code that you're going to be using multiple times. It saves you from the trouble of rewriting that code every time. Instead, you can just call a function.

A function always consists of the following parts:
<returntype> FunctionName ( argumentlist ) { /* Implementation */ }
The return type can be any type, from primitive datatypes like int and float to self-made objects, like BoilingPot. The function name pretty much explains itself, and the argument lets you define what values should be passed to a function. For example, if you were to make a multiplication function, you would want to pass the two values that you are going to multiply, and return the result value.

I hope this and other posts clears things up for you. If not, feel free to ask more ;)

##### Share on other sites
#include <iostream>#include <conio.h>using namespace std;int mult ( int x, int y );int main(){    int x;    int y;        cout << "Please enter the first number to be multiplied: ";    cin >> x;    cout << "Please enter the second number to be multiplied: ";    cin >> y;    cin.ignore();    cout << "The product of your two numbers is " << mult ( x, y) << endl;        getch();    return 0;}int mult ( int x, int y )// The int x, int y part, is causing the most confusion{    return x * y;}

##### Share on other sites
To add to my last post, it's mostly the variables in the brackets.

##### Share on other sites
int mult ( int x, int y )// The int x, int y part, is causing the most confusion{    return x * y;}

This code defines a function called mult. The first "int" shows that the function returns an integer number.
(int x, int y) means that the function takes 2 arguments, in this case this are 2 integer numbers.
The values of the two numbers will be copied to the x und y variables who will exist within the functions scope (the { } represent the functions scope).

So when you call the function with the following line:

mult(4, 2);

the programs runs the function, it creates two integer variables called x and y, it gives x the value 4 and y the value 2.
Now it multiplies x and y and returns the result.
To catch the result you would need to do the following:

int result = mult(4, 2);

result would be 8 in this case.

##### Share on other sites
In C++ everything is statically typed this means that when you compile your code, the compiler can tell what type every variable is (including function arguments)

This is why you must tell the compiler what type the parameters are, so it can check that you only perform actions which work with those types.
int mult( x, y ){    return x * y;}

Here we don't have the types so this won't compile. What would happen if we call this function by passing bools? Or what about passing an int with a string? These uses don't make any sense, so to prevent them, the compiler requires that you put the types, so it can check for things like that.

Some languages (like Pyhton) don't require that you specify types. To make up for this though, they have to do the type checking at run-time.

So basically, the types are so C++ can make sure you only do legal things with your variables and so it can check for this before the code is run.

##### Share on other sites
So your question is, how do the variables in the brackets get passed into the function? Or is there something else confusing you?

##### Share on other sites
Quote:
 Original post by CandleJackSo your question is, how do the variables in the brackets get passed into the function?...

That's pretty much it right there.

##### Share on other sites
When you say "cook eggs", you have to be told what eggs to cook.

So:
int multiply_integers( int x, int y ){  return x * y;}

Here we have a function "multiply_integers". When we call it, we have to say "what integers are we multiplying?"

In C and C++, this is described by the variables in the brackets. Let's look at the first line above:
int multiply_integers( int x, int y )

The name of the function is "multiply_integers" -- that is how you refer to the function when you want to use it later on.

To the left of the function name is the "return type" -- what kind of thing does the function produce? In this case, it produces an "int" (an integer -- a whole number).

To the right of the function name are brackets that contain types and names of parameters -- the intredients in your recipie.

In this case, multiply_integers requires two ingredients -- both of them are integers, and one of them will be called "x" and the other will be called "y".

By giving the parameters (or ingredients) names, it is easier to keep track of what we are doing inside the function itself.

Let's back up and look at the entire function now:
int multiply_integers( int x, int y ){  return x * y;}

The function is called "multiply_integers".
It makes an "int".
It has two ingredients -- both of them are "int"s, and they are called "x" and "y".

What it does is contained inside the squigly brackets (their actual name!)
{  return x * y;}

"return" just lets the language know "this is the return value of this function" -- it also ends the function.

When you use "multiply_integers", you use it like this:

void main(){  int result = 0;  result = multiply_integers( 3, 2 );}

The "3" becomes "x" within the multiply_integers function, and the "2" becomes "y". Notice that we didn't have to name anything "x" or "y" when we called multiply_integers.

Make sense?

##### Share on other sites
Thank you ALL for trying so hard, but it seems the harder I try the lass it makes sense. I think the easiest way would be to comment this code.
#include <iostream>#include <conio.h>using namespace std;int mult ( int x, int y );int main(){    int x;    int y;        cout << "Please enter the first number to be multiplied: ";    cin >> x;    cout << "Please enter the second number to be multiplied: ";    cin >> y;    cin.ignore();    cout << "The product of your two numbers is " << mult ( x, y) << endl;        getch();    return 0;}int mult ( int x, int y )// The int x, int y part, is causing the most confusion{    return x * y;}

##### Share on other sites
I think it is important to mention that the int x and int y are freshly created variables within the function and you only pass the value to them, else he might have trouble understanding the concept of passing by reference or pointers later on.

##### Share on other sites
Quote:
Original post by Kenny77
Quote:
 Original post by CandleJackSo your question is, how do the variables in the brackets get passed into the function?...

That's pretty much it right there.

Ok I'll try my best.

When you're running a program, the program's instructions stored in system memory are being executed in sequence. A function name is a pointer to another location with instructions, you when you call a function it begins to execute the instructions at that location.

This is where the stack and stack frames come in. The stack is where the local variables that haven't been dynamically allocated are stored. A stack frame is a portion of the stack allocated for a function call. It can be thought of as a node on the stack that contains all the local variables that are in the current scope. When you call a function, a new stack frame is created and it contains the return address (the location of instructions to return when the function is done), the paramters (the variables that are in the brackets), and local variables delcared inside the function body.

I know this might be a little confusing, so I can elaborate more if you are still confused. I've found that when learning about the stack a diagram can be pretty helpful. You can find one, along with much more information here: http://en.wikipedia.org/wiki/Stack_frame

##### Share on other sites
I'll comment my own code to give you an idea of what's giving me trouble.
#include <iostream>#include <conio.h>using namespace std;int mult ( int x, int y );// Variable declarations?int main(){    int x;    int y;        cout << "Please enter two numbers to be multiplied:  ";    cin >> x >> y;// Okay, enter two numbers    cin.ignore();    cout << "The product of your two numbers is " << mult ( x, y) << endl;    /*Whoa, wait a minute, where did this ( x, y ) come from and      how is it used*/        getch();    return 0;}int mult ( int x, int y )// How is this used{    return x * y;// Return x multiplied by y}

This is pretty embarassing, did anyone have this much trouble with functions?

##### Share on other sites
#include <iostream>int multiply( int a, int b ){  std::cout << "I'm multiplying " << a << " by " << b << '\n';  return a * b;}int main(){  int x = multiply( 3, 2 );  std::cout << "x is: " << x << '\n';  int y = multiply( 5, 15 );  std::cout << "y is: " << y << '\n';  int z = multiply( x, y );  std::cout << "z is: " << z << '\n';}

##### Share on other sites

include <iostream>#include <conio.h>using namespace std;/*This is the function prototype, to let the compiler know that this function exists and what it looks like.*/int mult ( int x, int y );int main(){    int x;    int y;        cout << "Please enter two numbers to be multiplied:  ";    cin >> x >> y;// Okay, enter two numbers    cin.ignore();    cout << "The product of your two numbers is " << mult ( x, y) << endl;    /*The x and y are the arguments you are passing to this function.      When you call a function, the values here are copied over to the function                       paramters.    */        getch();    return 0;}/*This is the function definition. Here is where you specify the function name,the parameter list the function will use (the part in the parentheses) and thefunction body continaing the instructions that are executed when the function is called.*//* x and y are basically local variables the function has access to. The valuesof these variables are specified by the values passed when the function is called.*/int mult ( int x, int y ){    return x * y;// Return x multiplied by y}

Does this help?

##### Share on other sites
Excellent, it just clicked. It helped to see it without the int's before the x and y. Thank you all. :)

##### Share on other sites
See this is where i get confused between functions and classes...

When programming the recipie NotAYakk posted above, wouldnt this be done with some kind of "medium boiled egg class" that is called by the "fancy egg class" which is initiated by main or recipie loop?

Apologies if im crazy here.

##### Share on other sites
Functions describe actions. Classes describe data types.

##### Share on other sites
Quote:
 Original post by bam104See this is where i get confused between functions and classes...When programming the recipie NotAYakk posted above, wouldnt this be done with some kind of "medium boiled egg class" that is called by the "fancy egg class" which is initiated by main or recipie loop?Apologies if im crazy here.

probably not. There are many ways to break an egg, and in object oriented programs, even more ways to arange your code and classes. But here's a few likely ideas.

Idea 1 - the cook.

You would have a Chef class which had functions for each of the recipes he knows how to make. Things like BoilEggsMedium and MakeFancyEggs.

Idea 2 - the kitchen model.

You would have a Utilsil and Appliance classes like Oven, Microwave, Spatula, etc (like audio, graphics and interface devices in games). These would be instantiate at program start as contained members of a Kitchen class. You would have a Recipe class or interface, and dozens of Recipe instances such as "Fancy Eggs" (these are kind of like AI scripts). You would have a Chef class, which nows how to "read" recipes and "use" kitchen equipment (this is kind of like the master controller / main opponent AI).

##### Share on other sites
For those confused about classes... Do you know what a struct is?

A struct and a class are the same thing. :)

Classes or Structs hold information.
Functions manipulate information.

...

Now, things do get blurry and confusing when you try more advanced things. Your Classes can have Functions attached to them (called Methods), and you can write Functors which are Classes that act as Functions.

But at the core -- Classes hold and define data. Functions manipulate and change data.

##### Share on other sites
Now I need help with global and local variables. I know that local variables are used in the function itself, and global variables can be used by all functions, but in this code, how does addNums get num1 and num2.
#include <iostream>#include <conio.h>using namespace std;int addNums( int num1, int num2 );int main(){    int num1, num2;        cout << "Enter the first number: ";    cin >> num1;    cout << "Enter the second number: ";    cin >> num2;    cout << "The numbers added equal: " << addNums ( num1, num2 ) << endl;        getch();    return 0;}int addNums( int num1, int num2 ){    return num1 + num2;}

##### Share on other sites
Quote:
 Original post by Kenny77Now I need help with global and local variables. I know that local variables are used in the function itself, and global variables can be used by all functions, but in this code, how does addNums get num1 and num2.

They are passed in via the main() function. The line:
cout << "The numbers added equal: " << addNums ( num1, num2 ) << endl;
passes whatever is set into num1 and num2 into the function addNums. In both the main function and the addNums function you are working with local variables.

##### Share on other sites
[source lang='cpp']#include <iostream>#include <conio.h>using namespace std;// our global variabelesint num1 = 10int num2 = 23;int addNums(int num1, int num2);int main(){   cout << "3 + 4 = " << addNums(3, 4) << endl;   cout << "Global values: num1 = " << num1 << " and num2 = " << num2 << endl;   getch();   return 0;}int addNums(int num1, int num2){   // be aware! although num1 and num2 are global variabeles,   // this function has local variabeles with the same name.   // What happens is that the local variabeles are used, which are   // set to 3 and 4 respectively when the function gets called.   // If the global vars had been used, the result would've been 33.   return num1 + num2;}

There's an example with global variabeles. Notice that local variabeles override global ones, e.g. when a function or scope has variabeles with the same name, the local ones are used. The global ones don't get overwritten, they're just not accessible at that moment. That's something to be aware of. Usually it's best to keep as little global stuff as possible, as dividing makes it easier to conquer, or so they say. :)

Go ahead and experiment, writing those values to the console from within main() and within addNums(). I'm sure you'll find out what's going on exactly.