Home | | Computer Science 11th std | C++: Returning from function

Example Program - C++: Returning from function | 11th Computer Science : Chapter 11 : Functions

Chapter: 11th Computer Science : Chapter 11 : Functions

C++: Returning from function

The return statement, The Returning values, The Returning by reference

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

 

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.

 

Syntax:

return expression/variable;

 

Example :  return(a+b);  return(a);

return; // to terminate the function

 

The Returning values:

 

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:


 

Returning Non-integer values

A string can also be returned to a calling statement.

 

Program 11.24

#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);

}

Output :

Example: Function with Non Integer Return Chennai

 

The Returning by reference

 

Program 11.25

#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);

}

Output:

The Value of N1 = 150 and n1Reference = 150

After n1 increased the Value of N1 = 151 and n1Reference = 151

 

Tags : Example Program , 11th Computer Science : Chapter 11 : Functions
Study Material, Lecturing Notes, Assignment, Reference, Wiki description explanation, brief detail
11th Computer Science : Chapter 11 : Functions : C++: Returning from function | Example Program


Privacy Policy, Terms and Conditions, DMCA Policy and Compliant

Copyright © 2018-2024 BrainKart.com; All Rights Reserved. Developed by Therithal info, Chennai.