A function is an independent piece of code that performs an action and can be called from other parts of your application.
Your program always has a 'main' function that is the core of your program. If you take for instance the basic hello world example that's always floating around everything happens in the main function;
Code:
#include <iostream>
using namespace std;
int main()
{
cout << "Hello World!" << endl;
//Don't even bother 'mentioning' system pause or whatever...
//learn to run it from the command prompt the way it was designed
return 0;
}
You could break out the part that actually prints out the text into it's own function. Each function has a 'signature' (which is just the basic way it looks/is defined:
RETURNTYPE FunctionName(ArgumentType1 ArgumentName1 etc etc).
Ok so if we think about this for a bit... to print out hello world (simplest way possible) we don't need to return anything (so return type is 'void'), and don't need to pass any arguments to the function so we could define the function like this:
Code:
void PrintHelloWorld()
{
cout << "Hello World!" << endl;
}
Now if you also wanted to print out another message in a different circumstance you could make another function
Code:
void PrintHowsItGoing()
{
cout << "How's it going?" << endl;
}
and you could then call these from within your program like this
Code:
int main()
{
BOOL myCheck = FALSE;
//imagine some code here that does something and sets MyCheck to Either TRUE or FALSE;
if(myCheck == TRUE)
PrintHelloWorld();
else
PrintHowsItGoing();
//other code here
}
You can also pass parameters to functions and get a value back from a function
Code:
int FunkyNumber(int a, int b)
{
int c = (a*3) + (b*2);
return c;
}
This function as you can see returns an 'int' (
int in front of the function name) and takes two arguments , namely 'int a' and 'int b'. Then inside the function it does 'something' with them to calculate some kind of funky number and returns that value.
You could call that like this:
Code:
...
int x = FunkyNumber(3,5);
//x now is (3*3) + (5*2) = 19
...
Now a function with 1 line of code is of course trivial and somewhat useless, But imagine if you will that you had to do 'something' that took 500 lines of code. And you had to perform this same operation in 10 different places in your code. You obviously would not want to copy & paste the same code 10 Times (5000 lines of code right there). This would make your code unnecessarily large and would make fixing a bug really hard (you'd have to remember to fix it in all 10 different places!)
So this is why functions are so handy - You can simply call that one 500 line function from everywhere you need it without having to retype everything, and if there's any bugs that require fixing etc, you can simply fix them in one central place.