Jan 17

Till now,we come across that we cannot give multiple return statements and functions can return only one value at a time. This means if we do so in programming,then compiler must flash an error message?

But program will be compiled successfully.

We’ll understand this with the help of examples.

Example 1.

main()
{
int i=10,j=20;
fun(i,j);
printf(”i= %d j= “%d”,i,j);
}
fun(int p,int q)
{
p= 2*q;
q=2*p;
return(p);
return(q);
}
Output
i=10,j=20
Explanation
A call to fun() from main() sends 10 and 20 to variables p and q. In fun(), p and q are calculated and return(p) is executed,which sends the control back to main() along with the value of p. But this value is not collected in any variable in main() it just gets ignored. As a result i and j stands unchanged at 10 and 20 respectively. The statement return(q) never gets execued,since the previous return statement will not allow the control to reach there.

Example 2.

main()
{
int i=10,j=20,k;
k=fun(i,j);
printf(”k= %d,k);
}
fun(int p,int q)
{
int a.b;
a=p-q;
b=p+q;
return(a,b);
}

Output
k=30
Explanation
Whenever we are attempt to return more than one value through the return statement,the last value gets returned. Thus in this case the value of b,i.e. 30 gets returned. Had the return statement been return(b,a),the value of a would have been returned.

Share and Enjoy:
  • Digg
  • del.icio.us
  • Facebook
  • Google Bookmarks
  • Blogplay
  • LinkedIn
  • MySpace
  • Reddit
  • RSS
  • Twitter

written by Shweta