Functions

Started by
29 comments, last by Xai 17 years, 6 months ago
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).
Advertisement
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?
Ever follow a recipie?

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.
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 ;)
#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;}  
To add to my last post, it's mostly the variables in the brackets.
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.
My Blog
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.

Hope that made some sense
So your question is, how do the variables in the brackets get passed into the function? Or is there something else confusing you?
Quote:Original post by CandleJack
So your question is, how do the variables in the brackets get passed into the function?...


That's pretty much it right there.

This topic is closed to new replies.

Advertisement