While learning programming you will often run into this two terms: function declaration and function definition.
To declare function we need to state function name, number and type of parameters and function return type. Function declaration must happen above main() function.
Then, below main function we will define function. That means we will write that dedicated source about what job function will achieve. It's like going into great detail what and how function will do something.
In the example below we are declaring function printStuff() with void (function will do simple printing), and she has no parameters. Parameters are inputs for function. This is simple printing, so no need for them at the moment.
Then, below main() program function we have source code what that function will actually do. In this case it will just print "Hack The Planet" on our screens. Simple as that.
Run this code:
#include <iostream>
#include <cstdlib>
using namespace std;
void printStuff();
int main() {
printStuff();
return 0;
}
void printStuff() {
cout << "Hack The Planet" << endl;
}
Result:
Hack The Planet
Process returned 0 (0x0) execution time : 0.021 s
Press any key to continue.
Now, in the example below, we can have full function source before main() part of the program. Function function_1() will print one line on screen.
But also we have declaration of function_2(). That function will also do simple printing, but it will be defined below main() part of the program.
We can combine these two approaches if we need that:
#include <iostream>
#include <cstdlib>
using namespace std;
void function_1() {
cout << "I am from function_1" << endl;
}
void function_2();
int main() {
function_1();
function_2();
return 0;
}
void function_2() {
cout << "But, I am from function_2" << endl;
}
Result:
I am from function_1
But, I am from function_2
Process returned 0 (0x0) execution time : 0.223 s
Press any key to continue.
No comments:
Post a Comment