What is a function? A function is a group of statements that is executed when it is called from some point of the program.
As of now, I'm assuming the only function you've worked with is the main one.
int main ()
{
}
If this were the only function available in c++ code would get very long, sloppy and hard to read, lucky, c++ allows you to create multiple functions. Lets learn how.
First, you'll need a type name (parameters are optional we'll get into later) and brackets. So it'll look something like this.
type name ( parameter1, parameter2, ...) { statements }
*type is the data type specifier of the data returned by the function.
(Int, void, float etc.)
* name is the identifier by which it will be possible to call the function.
(int main name this yourself. example int newfunction () )
* parameters - Next lesson
*statements is the function's body. It is a block of statements surrounded by braces { }.
Lets see you would call a new function and how it works!
in order to call a function, it needs to be placed BEFORE the main function or you will get a c++ error because remember, c++ does the MAIN function first!
inside of the brackets can be whatever you want! Lets cout some words for an example.
int function ()
{
cout << "Hi";
}
int main ()
{
return 0;
}
If you complied the example above, you'll notice that you get an error, the reason for that is you haven't called the function, here's how you would call a created function in c++
int function ()
{
cout << "Hi";
}
int main ()
{
function (); - Type the NAME of the function and the "()" and end it with
a semi colon!
return 0;
}
*Note that when calling a function it will have to end with a semicolon. Play around with this and create your own functions.
Results 1 to 1 of 1
- 29 Apr. 2010 07:28pm #1
Understanding functions in c++ (I)