A function is called by providing the function name. When a program calls a function, program control is transferred to the called function. A called function performs defined task and when it's return statement is executed or when its function ending or closing brace is reached, it returns program control back to the main program.
If a function is to use arguments, it must declare variables that accept the values of the arguments. While calling a function there are two ways that arguments can be passed to a function :
The call by value method copies the values of actual parameters into the formal parameters, that is, the function creates its own copy of argument values and then uses them so, explain this in one simple example :
int main(){
int cube(int);
int vol,side=7;
vol = cube(side)
cout<<vol;}
int cube(int a){
return a*a*a;}
Output : 343
The main benefit of call by value method is that you cannot alter the variables that are used to call the function because any change that occurs inside function is on the functions copy of the argument value.
The call by reference method uses a different mechanism. In place of passing a value to the function being called , a reference to the original variable is passed so, explain again this in one another simple example :
int main{
void change(int &);
int a=4;
cout<< " a = "<<a;
change(a);
cout<< "\ta = "<<a;}
void change(int &z){z=10;
cout<< "\ta = "<<z;}
Output : a=4 a=10 a=10
Now, here a value is changed by change() function and set the address 4 to 10.
A function terminates when either a return statement is encountered or the last statement in the function is executed. Generally, a return statement is used to terminate a function whether or not it returns a value.
The return statement is useful in two ways. First, an immediate exit from the function is caused as soon as a return statement is encountered and the control passes back to the operating system which is mains caller. Second use of return a value to the calling code.
|
It's a special area where you can find special questions and answers for CSE students or IT professionals. Also, In this section, we try to explain a topic in a very deep way.