return in C++
The return statement takes control out of the function itself. It is stronger than a break. It is used to terminate the entire function after the execution of the function or after some condition.
Every function has a return statement with some returning value except the void() function. Although void() function can also have the return statement to end the execution of the function.
Syntax
return expression;
Examples of return
Example 1: Below is the program to demonstrate the return statement.
C++
// C++ program to demonstrate the // return statement #include <iostream> using namespace std; // Driver code int main() { cout << "Begin " ; for ( int i = 0; i < 10; i++) { // Termination condition if (i == 5) return 0; cout << i << " " ; } cout << "end" ; return 0; } |
Begin 0 1 2 3 4
Explanation
The above program starts execution by printing “Begin” and then the for loop starts to print the value of, it will print the value of i from 0 to 4 but as soon as i becomes equal to 5 it will terminate the whole function i.e., it will never go to print the “end” statement of the program.
Note: The return in void() functions can be used without any return type.
Example 2: Below is the program to demonstrate the return statement in void return type in function:
C++
// C++ program to demonstrate the return // statement in void return type function #include <iostream> using namespace std; // Function to find the greater element // among x and y void findGreater( int x, int y) { if (x > y) { cout << x << " " << "is greater" << "\n" ; return ; } else { cout << y << " " << "is greater" << "\n" ; return ; } } // Driver Code int main() { // Function Call findGreater(10, 20); return 0; } |
20 is greater
Jump statements in C++
Jump statements are used to manipulate the flow of the program if some conditions are met. It is used to terminate or continue the loop inside a program or to stop the execution of a function.