c++-goto-statement

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++.

Contents Overview:

Definition of a 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:

goto statement in C++ Example

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++

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:

Example 1: Input Validation Using goto

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.

Illustration 2: Endless Loop Using goto

Cpp

Code Copied!

var isMobile = window.innerWidth ");

editor40816.setValue(decodedContent); editor40816.clearSelection();

editor40816.setOptions({ maxLines: Infinity });

function decodeHTML40816(input) { var doc = new DOMParser().parseFromString(input, "text/html"); return doc.documentElement.textContent; }

// Function to copy code to clipboard function copyCodeToClipboard40816() { const code = editor40816.getValue(); navigator.clipboard.writeText(code).then(() => { jQuery(".maineditor40816 .copymessage").show(); setTimeout(function() { jQuery(".maineditor40816 .copymessage").hide(); }, 2000); }).catch(err => { console.error("Error copying code: ", err); }); } ``````javascript { jQuery("".maineditor40816 .copymessage"").hide(); }, 2000); }).catch(err => { console.error(""Error copying code: "", err); });

function executeCode40816() {

var code = editor40816.getSession().getValue();

jQuery(""#runBtn40816 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("".output40816"").html("<pre>" + data + "</pre>"); jQuery("".maineditor40816 .code-editor-output"").show(); jQuery(""#runBtn40816 i.run-code"").hide(); } });

}

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:

Example 2: Infinite Loop Using goto

The code illustrates how an infinite loop is generated with goto, which continuously jumps back to the loop_start label, subsequently printing the message &ldquo;Welcome to Intellipaat&rdquo; indefinitely.

Example 3: Exiting Nested Loops

Cpp

Code Copied!

var isMobileView = window.innerWidth { jQuery("".maineditor2384 .copymessage"").show(); setTimeout(function() { jQuery("".maineditor2384 .copymessage"").hide(); }, 2000); }).catch(err => { console.error(""Error copying code: "", err); }); }

function executeCode2384() {

var code = editor2384.getSession().getValue();

jQuery(""#runBtn2384 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("".output2384"").html("<pre>" + data + "</pre>"); jQuery("".maineditor2384 .code-editor-output"").show(); jQuery(""#runBtn2384 i.run-code"").hide(); } });

}

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:

Example 3: Breaking Out of Nested Loops

The code demonstrates how goto is utilized to break out of both nested loops when i == 2 &amp;&amp; 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!");

jQuery(".maineditor29736 .copymessage").show(); setTimeout(function() { jQuery(".maineditor29736 .copymessage").hide(); }, 2000); }).catch(err => { console.error("Error copying code: ", err); }); }

function runCode29736() {

var code = editor29736.getSession().getValue();

jQuery("#runBtn29736 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(".output29736").html("

"+data+"");
									jQuery(".maineditor29736 .code-editor-output").show();
									jQuery("#runBtn29736 i.run-code").hide();

} })

}

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:

Example 4: Conditional Branching using goto

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!");

jQuery(".maineditor22349 .copymessage").show(); setTimeout(function() { jQuery(".maineditor22349 .copymessage").hide(); }, 2000); }).catch(err => { console.error("Error copying code: ", err); }); }

function runCode22349() {

var code = editor22349.getSession().getValue();

jQuery("#runBtn22349 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(".output22349").html("

"+data+"");
									jQuery(".maineditor22349 .code-editor-output").show();
									jQuery("#runBtn22349 i.run-code").hide();

} })

}

function closeoutput22349() { var code = editor22349.getSession().getValue(); jQuery(".maineditor22349 .code-editor-output").hide(); }

// Bind event listeners to the buttons document.getElementById("copyBtn22349").addEventListener("click", copyCodeToClipboard22349); document.getElementById("runBtn22349").addEventListener("click", runCode22349); document.getElementById("closeoutputBtn22349").addEventListener("click", closeoutput22349);


``````html
copyCodeToClipboard22349);
document.getElementById("runBtn22349").addEventListener("click", runCode22349);
document.getElementById("closeoutputBtn22349").addEventListener("click", closeoutput22349);

Result:

Example 5: Simple Menu Using goto

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.

The article C++ goto Statement first appeared on Intellipaat Blog.

```


Leave a Reply

Your email address will not be published. Required fields are marked *

Share This