22
DecGoto and Return Statements in C++
21 May 2024
Beginner
2.05K Views
7 min read
Goto and Return Statements in C++: An Overview
In the previous C++ tutorial on jump statements, we saw the break and continue statements in C++ in complete detail. It's now time to move on to the other two important jump statements,goto
and return
statements in C++. If you want to become a certified C++ programmer, you can also consider our C++ Certification Course.Goto Statement in C++
It is a control flow mechanism that enables programmers to move the execution of a program to a particularlabeled
statement inside the code. The goto
statement in C++ allows one to skip over the customary sequential flow of the code and go to a specific location within it. The best practice is to avoid the requirement for goto
statements whenever possible by using structured programming elements like loops and conditionals.Syntax
goto label;
// ...
label:
// Statement(s) to execute
Example to demonstrate goto statement in C++ Compiler
#include <iostream>
using namespace std;
int main() {
int choice;
cout << "Select an option:" << endl;
cout << "1. Print 'Hello'" << endl;
cout << "2. Print 'World'" << endl;
cout << "3. Exit" << endl;
cin >> choice;
switch (choice) {
case 1:
cout << "Hello" << endl;
break;
case 2:
cout << "World" << endl;
break;
case 3:
cout << "Exiting..." << endl;
goto end; // Jump to the 'end' label to exit
default:
cout << "Invalid choice" << endl;
break;
}
// This is where the 'end' label is defined
end:
cout << "Program ends here." << endl;
return 0;
}
- This C++ program gives the user a menu to select an option.
- Depending on what they select, the program either prints "Hello," "World," or ends.
- When the user chooses the
exit
option3
, thegoto
statement is used to leap to theend
label, enabling the program to end and output "Programme ends here."
Output
Select an option:
1. Print 'Hello'
2. Print 'World'
3. Exit
- If the user enters 1st choice
Output
Hello Program ends here.
- If the user enters 2nd choice
Output
World Program ends here.
- If the user enters 3rd choice
Output
Exiting... Program ends here.
Read More - C++ Interview Questions Interview Questions for Freshers
Return Statement in C++
When a function is finished running, thereturn
statement in C++ is used to give the caller a value. It is often used to return a result to the caller code.Syntax
return expression;
Example to demonstrate return statement in C++
#include <iostream>
using namespace std;
int multiply(int a, int b) {
return a * b;
}
int main() {
int result = multiply(5, 7);
cout << "The product is: " << result << endl;
return 0;
}
- Here, the
main()
function calls themultiply()
function to multiply the values 5 & 7. - The
multiply()
function multiplies the values and returns the product to themain()
function.
Output
The product is: 35
Discover more about functions
and use of the return
statement in the section, Functions in C++, Call by Value and Call by Reference in C++.