Wednesday, 4 December 2013

Return Function

#include <iostream>
using namespace std;
int addition (int a, int b)
{
  int r;
  r=a+b;
  return r;

}

int main ()
{
  int a,b,z;
  cout<<"Enter First Number"<<endl;
  cin>>a;
  cout<<"Enter Second Number"<<endl;
  cin>>b;
  z=addition(a,b);
  cout <<"The result is"<<z;

 
}
In this program,We will discuss Return  Function....!!
 first of all remember something said at the beginning of this tutorial: a C++ program always begins its execution by the main function. So we will begin there.

We can see how the main function begins by declaring the variable z of type int. Right after that, we see a call to a function called addition. Paying attention we will be able to see the similarity between the structure of the call to the function and the declaration of the function itself some code lines above: 

 

The parameters and arguments have a clear correspondence. Within the main function we called to additionpassing two values: 5 and 3, that correspond to the int a and int b parameters declared for function addition.

At the point at which the function is called from within main, the control is lost by main and passed to functionaddition. The value of both arguments passed in the call (5 and 3) are copied to the local variables int a and int b within the function.

Function addition declares another local variable (int r), and by means of the expression r=a+b, it assigns to rthe result of a plus b. Because the actual parameters passed for a and b are 5 and 3 respectively, the result is 8.

The following line of code:

return r;
finalizes function addition, and returns the control back to the function that called it in the first place (in this case,main). At this moment the program follows its regular course from the same point at which it was interrupted by the call to addition. But additionally, because the return statement in function addition specified a value: the content of variable r, which at that moment had a value of 8. This value becomes the value of evaluating the function call.   So being the value returned by a function the value given to the function call itself when it is evaluated, the variable z will be set to the value returned by addition (5, 3), that is 8. To explain it another way, you can imagine that the call to a function (addition (5,3)) is literally replaced by the value it returns (8).
I think you got it.........!!!
Feel free to give suggestions in comment box.......!

0 comments: