Loading....
Coupon Accepted Successfully!

 

Returning from a Function

  • A return statement is used when a function to be terminated whether or not it returns a value.

  • It is used as an immediate exit from the function.

  • While the return statement is used it returns back the control to the main function.

  • A function may contain several return statements.

Program

#include<iostream.h>

int f();

int f(int);

void main()

{

int x;

cout<<"\n enter the value of x";

cin>>x;

cout<<"f()="<<f();

cout<<"f(x)="<<f(x);

}

int f()

{

return(100);

}

int f(int a)

{

return(a * a);

}

Return by reference

  • Return by reference returns a globally declared variable to the calling function.

  • The call statement must be in the left hand side of an assignment statement.

  • The right hand side value will be assigned to the returned reference variable.

  • The general format of function declarations is given below.

datatype &function_name(type 1&, type 2&,......)

Where
& - reference operator
Type 1& - valid datatype and are optional.
The function definition general format is

datatype &function_name(type 1 &var1, type2 &var2,......)

{

-----

-------

 

}

Where
&- reference operators.
Function calling
  • The general format of function calling is
Function_name(var1, var2.....)=expression
Note: only the function returning a reference can appear on the left-hand side of an assignment operator.

 





Test Your Skills Now!
Take a Quiz now
Reviewer Name