A function is a module in a program that structures the program and breaks it up into logical sections. Take this long main function for an example. (I know it's not long, bear with me).
Code:
#include <iostream>
#include <cmath>
int main ( void )
{
int n = 1, input;
std::cout<<"The number is "<< n <<"\n";
// Ask for the user to enter a number
// and add that number to n
std::cout<<"Enter a number to add\n";
std::cin>>input;
n += input;
std::cout<<"The number is "<< n <<"\n";
// Calculate n to the user selected power
std::cout<<"Enter a power to raise n to\n";
std::cin>>input;
n = pow ( n, input );
std::cout<<"The number is "<< n <<"\n";
return 0;
}
That's kind of ugly and we can do better by taking the operations and breaking them up into logical parts.
Code:
#include <iostream>
#include <cmath>
void printResult ( int x )
{
std::cout<<"The number is "<< x <<"\n";
}
int getInput ( void )
{
int input;
std::cout<<"Enter a number\n";
std::cin>>input;
return input;
}
void add ( int& x )
{
x += getInput();
}
void raise ( int& x )
{
int i = getInput();
x = pow ( x, i );
}
int main ( void )
{
int n = 1;
printResult ( n );
add ( n );
printResult ( n );
raise ( n );
printResult ( n );
return 0;
}
That's much easier to follow and we don't need the comments anymore because the function names perform that duty. Anytime you feel you need to use goto, you can easily add a function because they both do something similar, go there and execute that code. The difference between functions and goto is that goto doesn't come back. A function will return to the same line that you called it, thus allowing you to execute code after the call without setting another label and calling goto again.
I could go on and on about functions, so you might want to be more specific in what you don't understand.
-Prelude