Monday 30 May 2016

Formal and Actual Parameters in C++

Functions are of utmost usage in any language. They are like errand boys for our program. We give them orders and they just take care of things all by them selves. What's so great about functions is the fact that they can be used to do the same thing but on a variety of inputs. This part is called taking orders (or giving, depends on perspective) i.e. doing the same thing/ calculation on different different inputs. These inputs are called parameters. But wait, aren't they called arguments? Well there is indeed a clear distinction between the two (it's minute but clear). Let's get into it then:
I'll say it once and for all, the things that functions take (like orders) and work on them to return stuff are called parameters. But, there are two kinds of parameters:

Formal Parameters:
When we define a function, along with the function signature (it's name) and the return type, we also specify a list of parameters that the function takes. 
type name(parameter list)
This parameter list contains a comma separated list (of course) of variables and their types. These variables are then used inside the function body to write the code and return stuffs as well. 
int add(int x, int y)
These are what we call as formal parameters. Simply put, these are just identifiers that don't have values as of yet but represent what we intend to do with these values if and when we would get them via a function call. 

Actual Parameters:
After a function has been declared and defined it's time to use them. Using a function is exactly like firing orders at an errand boy. And part of the job of calling a function includes giving them some actual values to work with. These values will take the position of formal parameters. Calculations would then proceed based on these values. 
add(2, 3);
These are called actual parameters or arguments. Remember an argument must be a value (not necessarily a literal like 2 or 3). It can either be a straight out value like in the above case or it can be another variable containing some value in turn.
int a, b;
a=2;
b=3;
add(a, b);

No comments:

Post a Comment