codescracker


c++

C++ Return from Function



« Previous Tutorial Next Tutorial »


As invoking a function is important, returning from a function is equally important as it not only terminates the function's execution but also passes the control back to the calling function. A function terminates when either a return statement is encountered or the last statement in the function is executed. Generally, a return statement is used to terminate a function whether or not it returns a value.

C++ return Statement

The return statement is useful in two ways. Firs, an immediate exit from the function is caused as soon as a return statement is encountered and the control passes back to the operating system which is main's caller. Second use of return statement is that it is used to return a value to the calling code.

Even though it is not necessary to have a return statement in a function, most functions rely on the return statement to stop the execution either because a value must be returned or to make function's code simpler and more efficient.

A function may contain several return statements. However, only one of them gets executed because the execution of the function terminates as soon as a return is encountered. Following program uses multiple return statements.

C++ Return from Function Example

Following program check whether a given character is contained in a string or not and find its position :

/* C++ Return from a Function */

#include<iostream.h>
#include<conio.h>

int findpos(char str[], char ch);

void main()
{
	clrscr();
	char string[80], ch;
	int y = 0;
	cout<<"Enter main string:\n";
	cin.getline(string, 80);
	cout<<"\nEnter character to be searched for:\n";
	cin.get(ch);
	y = findpos(string, ch);
	if(y == -1)
	{
		cout<<"\nSorry! character is not in the string\n";
	}
	getch();
}
int findpos(char s[], char c)
{
	int flag = -1 ;
	for(int i = 0 ; s[i] != '\0' ; i++)
	{
		if(s[i] == c)
		{
			flag = 0;
			cout<<"\nThe character is in the string at position " << i+1 ;
		}
	}
	return(flag);
}

When the above C++ program is compile and executed, it will produce the following output:

c++ return from function

In the above program, the function findpos checks whether a character contained in a string or not. As soon as the character is found in the string, the function terminates returning the position of the character. Otherwise, a value-1 is returned depicting that the character is not found. There are two return statements in findpos but only one of them gets executed at a time.


« Previous Tutorial Next Tutorial »



Tools
Calculator

Quick Links
Signup - Login - Give Online Test