Global and Local Function Declaration
Understanding global and local function declaration using a function declaration above main and another inside the main routine.
Learning Objectives
- Understanding how a global function declaration can be used in many functions while local declaration limits a function use within a given scope only.
Source Code
|
|
Run Output
Code Understanding
int action1(int,int);
This function is declared outside main() routine so it can be used in any function and main().
int main() {
int action2(int,int);
This function is declared inside the main routine, so its usage is limited to this routine only.
int a=10,b=15; cout<<action2(a,b)<<endl;
Initial value of a and b are set and the function declared locally is applied. Although this function is declared locally but its code has to be written outside only.
cout<<action1(a,b)<<endl;
The function action1 is declared globally so it can be used in main() as well as in any other routine.
int action1(int x,int y){
//int n=action2(x,y);
This is not allowed and if uncommented will give error as this function action2() was meant to be used inside main only.
return x*y; //Returns multiplication of given parameters x and y.
}
int action2(int x,int y) {return x+y;}
This is function definition of a function declared inside the main routine. Its definition can not be given inside main but its call can only be made by main routine only.
Notes
- concept of internal declaration within main or any other function itself provides restricted access to functions. This concept is well handled when the classes and oops concepts of c++ are used.
Suggested Filename(s): fn-global-local.cpp,fngloloc.cpp
Created: 17-Jan-2018 00:13 | Updated: 17-Jan-2018 00:25|
