![]() |
What are functions?
A function is a sub-program that can be written for use in places where a certain
action needs to be taken more than once. This prevents copying and pasting of code
and it allows for dynamic programs.
How are functions defined?
Functions take the form :
Contents of main.cpp : #include <iostream> #include <stdlib.h> using namespace std;
Our first function is a function named sayHello. It
does not return a value and therefore the keyword void
is used. void sayHello() { cout << "Hello" << endl; }
A function always needs to be declared before it can be used. Our functions
are being used within our main method. If we want to declare a function at the
end of the source file, we need to let the main method know that another function
exists.
void sayGoodbye();
When calling a function, you use the following :
int main() { sayHello(); sayGoodbye(); system("pause"); return 0; } We can now define what our function does. In our example, all it does is print the string Goodbye. void sayGoodbye() { cout << "Goodbye" << endl; } You should now be able to create basic functions that contain no parameters. This should make your programs more readable and modular. Please let me know of any comments you may have : Contact Me
All Rights Reserved, © Zeus Communication, Multimedia & Development 2004-2005 Read the Disclaimer |
|