Returning
from function
Returning
from the function is done by using the return
statement.
The
return statement stops execution and
returns to the calling function. When a return
statement is executed, the function is terminated immediately at that
point.
The
return statement is used to return
from a function. It is categorized as a jump statement because it terminates
the execution of the function and transfer the control to the called statement.
A return may or may not have a value
associated with it. If return has a value associated with it, that value
becomes the return value for the calling statement. Even for void function
return statement without parameter can be used to terminate the function.
return expression/variable;
Example : return(a+b); return(a);
return;
// to terminate the function
The
functions that return no value is declared as void. The data type of a function
is treated as int, if no data type
is explicitly mentioned. For example,
For Example :
int add (int, int);
add (int, int);
In
both prototypes, the return value is int, because by default the return value
of a function in C++ is of type int.
Look at the following examples:
A
string can also be returned to a calling statement.
#include<iostream>
#include<string.h>
using namespace std;
char *display()
{
return (“chennai”);
}
int main()
{
char s[50];
strcpy(s,display());
cout<<”\nExample:Function
with Non Integer Return”<<s;
return(0);
}
Example: Function with Non Integer Return Chennai
#include<iostream>
using namespace std;
int main()
{
int n1=150;
int &n1ref=n1;
cout<<"\nThe
Value of N1 = "<<n1<<" and n1Reference =
"<<n1ref;
n1ref++;
cout<<"\nAfter
n1 increased the Value of N1 = "<<n1;
cout<<"
and n1Reference = "<<n1ref;
return(0);
}
The Value of N1 = 150 and n1Reference = 150
After n1 increased the Value of N1 = 151 and n1Reference = 151
Related Topics
Privacy Policy, Terms and Conditions, DMCA Policy and Compliant
Copyright © 2018-2024 BrainKart.com; All Rights Reserved. Developed by Therithal info, Chennai.