The goto statement in C++ is a control flow element that facilitates unconditional transitions to a designated section of a program within the same function. Despite being a constituent of the C++ programming language, the use of the goto statement is typically discouraged in contemporary C++ development. In this piece, we shall explore what a goto statement entails, alongside its syntax, characteristics, illustrations, drawbacks, appropriate use cases, reasons for avoiding it, and preferred substitutes for the goto statement in C++.
A goto statement in C++ acts as a control flow mechanism enabling programs to leap or transition to another section within the same function. It permits an unconditional jump in the identical function. Moreover, upon executing a goto statement, control is transferred immediately to the specified label, bypassing the intervening code. Recommended structured alternatives encompass loops, conditional statements, and exception handling, as opposed to utilizing a goto statement.
Syntax for a goto statement in C++
The general syntax for a goto statement in C++ is as follows:
goto label; // ... some code ... label: // code to execute following jump
In this example, the label is a user-defined identifier succeeded by a colon (:), which indicates the targeted area in the code.
Example:
Cpp
Code Copied!
var isMobile = window.innerWidth “);
editor64142.setValue(decodedContent); // Set the default text
editor64142.clearSelection();
editor64142.setOptions({
maxLines: Infinity
});
function decodeHTML64142(input) {
var doc = new DOMParser().parseFromString(input, “text/html”);
return doc.documentElement.textContent;
}
// Function to copy code to clipboard
function copyCodeToClipboard64142() {
const code = editor64142.getValue(); // Get code from the editor
navigator.clipboard.writeText(code).then(() => {
jQuery(“.maineditor64142 .copymessage”).show();
setTimeout(function() {
jQuery(“.maineditor64142 .copymessage”).hide();
}, 2000);
}).catch(err => {
console.error(“Error copying code: “, err);
});
}
function runCode64142() {
var code = editor64142.getSession().getValue();
jQuery(“#runBtn64142 i.run-code”).show();
jQuery(“.output-tab”).click();
jQuery.ajax({
url: “https://intellipaat.com/blog/wp-admin/admin-ajax.php”,
type: “post”,
data: {
language: “cpp”,
code: code,
cmd_line_args: “”,
variablenames: “”,
action:”compilerajax”
},
success: function(response) {
var myArray = response.split(“~”);
var data = myArray[1];
jQuery(“.output64142”).html(“
"+data+"");
jQuery(".maineditor64142 .code-editor-output").show();
jQuery("#runBtn64142 i.run-code").hide();
}
});
}
function closeoutput64142() {
var code = editor64142.getSession().getValue();
jQuery(".maineditor64142 .code-editor-output").hide();
}
// Attach event listeners to the buttons
document.getElementById("copyBtn64142").addEventListener("click", copyCodeToClipboard64142);
document.getElementById("runBtn64142").addEventListener("click", runCode64142);
document.getElementById("closeoutputBtn64142").addEventListener("click", closeoutput64142);
Output:
The displayed code demonstrates how the goto skip; statement enables the program to jump straight to the skip: label while omitting the line “This will not be printed”, and then the execution continues from the label, displaying “After goto”.
```html
Flowchart of a goto Statement in C++
Characteristics of the C++ goto statement
It redirects control to a labeled statement unconditionally.
The goto as well as the designated label must reside within the same function.
A label is an identifier concluded with a colon(:).
The code located between the goto and its label is bypassed during execution.
Illustrations of goto Statement in C++
Presented below are several illustrations of goto statements in C++:
Illustration 1: Input Verification Using goto
Cpp
Code Copied!
Result:
This code demonstrates the use of a goto statement to repeatedly prompt the user until a valid age input, ranging from 0 to 120, is provided, at which point the outcome is displayed in the console.
function hideOutput40816() {
var code = editor40816.getSession().getValue();
jQuery("".maineditor40816 .code-editor-output"").hide();
}
// Bind event handlers to the buttons
document.getElementById(""copyBtn40816"").addEventListener(""click"", copyCodeToClipboard40816);
document.getElementById(""runBtn40816"").addEventListener(""click"", executeCode40816);
document.getElementById(""closeoutputBtn40816"").addEventListener(""click"", hideOutput40816);
Output:
The code illustrates how an infinite loop is generated with goto, which continuously jumps back to the loop_start label, subsequently printing the message “Welcome to Intellipaat” indefinitely.
function hideOutput2384() {
var code = editor2384.getSession().getValue();
jQuery("".maineditor2384 .code-editor-output"").hide();
}
// Bind event listeners to the buttons
document.getElementById(""copyBtn2384"").addEventListener(""click"", copyCodeToClipboard2384);
document.getElementById(""runBtn2384"").addEventListener(""click"", executeCode2384);
document.getElementById(""closeoutputBtn2384"").addEventListener(""click"", hideOutput2384);
Output:
The code demonstrates how goto is utilized to break out of both nested loops when i == 2 && j == 2, thereafter continuing execution at the exit_loops label to display a message and output.
Example 4: Conditional Branching using goto
Cpp
Code Copied!
``````html
var isMobile = window.innerWidth ");
editor29736.setValue(decodedContent); // Set the default text
editor29736.clearSelection();
editor29736.setOptions({
maxLines: Infinity
});
function decodeHTML29736(input) {
var doc = new DOMParser().parseFromString(input, "text/html");
return doc.documentElement.textContent;
}
// Function to duplicate code to clipboard
function copyCodeToClipboard29736() {
const code = editor29736.getValue(); // Fetch code from the editor
navigator.clipboard.writeText(code).then(() => {
// alert("Code copied to clipboard!");
function closeoutput29736() {
var code = editor29736.getSession().getValue();
jQuery(".maineditor29736 .code-editor-output").hide();
}
// Bind event listeners to the buttons
document.getElementById("copyBtn29736").addEventListener("click", copyCodeToClipboard29736);
document.getElementById("runBtn29736").addEventListener("click", runCode29736);
document.getElementById("closeoutputBtn29736").addEventListener("click", closeoutput29736);
Result:
The snippet demonstrates how a goto statement can be utilized to redirect to either even or odd labels depending on the user's input, and subsequently displays the outcome in the console.
Example 5: Basic Menu Using goto
Cpp
Code Copied!
var isMobile = window.innerWidth ");
editor22349.setValue(decodedContent); // Set the default text
editor22349.clearSelection();
editor22349.setOptions({
maxLines: Infinity
});
function decodeHTML22349(input) {
var doc = new DOMParser().parseFromString(input, "text/html");
return doc.documentElement.textContent;
}
// Function to duplicate code to clipboard
function copyCodeToClipboard22349() {
const code = editor22349.getValue(); // Fetch code from the editor
navigator.clipboard.writeText(code).then(() => {
// alert("Code copied to clipboard!");
The script illustrates the application of the goto statement to present a menu and manage user input until the user selects the exit option, after which it logs the outcome to the console.
When to Apply the goto Statement in C++
Here are several scenarios in which a goto statement is applied in C++:
Exiting from deeply nested loops; when a scenario requires escaping multiple nested loops or conditionals simultaneously, a goto statement can simplify the process.
Error management in low-level C++ programming.
When there's a necessity to jump to a cleanup section of the code before returning a value.
Motives to Evade the goto Statement in C++
This section will cover various drawbacks of utilizing the goto statement in C++.
A goto statement complicates the comprehensibility of the code.
It disregards contemporary programming principles promoting clarity, modularity, and control flow best practices.
It can bypass the constructor and destructor, resulting in memory leaks and issues with resource management.
It is better to avoid it due to the existence of superior alternatives, such as loops, conditionals, exceptions, and functions, which enhance code reusability, safety, and readability.
Recommended Substitutes for the goto Statement in C++
Use Case
Recommended Substitute
Reasons These Are Superior to goto
Looping
for, while, do-while
These loop constructs are organized, straightforward, and easier to control.
Exiting nested loops
break, return
These provide a clean exit without disarraying the code flow.
Skipping code sections
continue, if-else
Simplifies the flow of code and makes it predictable.
Error management
try-catch, RAII
More secure, ensuring proper resource cleanup.
Reusing input logic
Loop with condition
No manual jumps needed; utilize an appropriate loop instead.
Cleanup before return
RAII, smart pointers
They automatically manage cleanup, rendering goto unnecessary.
Final Thoughts
The goto statement in C++ allows switching to a labeled location in the same function. While it has practical uses, it's generally advised against using it for several reasons. Additionally, there are numerous disadvantages associated with the goto statement, making it preferable to opt for alternatives like loops and conditional structures. By comprehending the purpose of a goto statement, along with when to employ it and when to forgo it, you can effectively craft C++ programs utilizing the goto statement.
C++ goto Statement – FAQs
Q1. Is the goto statement endorsed in modern C++?
No, it's generally not endorsed in contemporary C++, except in specific situations like breaking out of nested loops or managing low-level errors.
Q2. Can a goto statement traverse between two functions?
No, a goto statement is limited to jumping within the same function.
Q3. What are substitutes for goto?
Suitable substitutes for the goto statement include loops, break, continue, return, and exceptions.
Q4. Does goto impact destructors?
Yes, a goto statement can bypass destructors and disrupt RAII if misapplied.
Q5. Is goto quicker than loops or conditionals?
No, the goto statement is not inherently faster than loops or conditionals, although there may be minimal performance differences in certain scenarios.
To provide the best experiences, we use technologies like cookies to store and/or access device information. Consenting to these technologies will allow us to process data such as browsing behavior or unique IDs on this site. Not consenting or withdrawing consent, may adversely affect certain features and functions.
Functional
Always active
The technical storage or access is strictly necessary for the legitimate purpose of enabling the use of a specific service explicitly requested by the subscriber or user, or for the sole purpose of carrying out the transmission of a communication over an electronic communications network.
Preferences
The technical storage or access is necessary for the legitimate purpose of storing preferences that are not requested by the subscriber or user.
Statistics
The technical storage or access that is used exclusively for statistical purposes.The technical storage or access that is used exclusively for anonymous statistical purposes. Without a subpoena, voluntary compliance on the part of your Internet Service Provider, or additional records from a third party, information stored or retrieved for this purpose alone cannot usually be used to identify you.
Marketing
The technical storage or access is required to create user profiles to send advertising, or to track the user on a website or across several websites for similar marketing purposes.