Question
Asked 6th Mar, 2014

What is the best alternatives for "goto" statements in C++?

I am facing some issues with memory usage and programming flow using goto statements. How can I avoid them and be more efficient. (I am using QT Creator) for programming.

Most recent answer

9th Aug, 2015
Hossein Afshari
Nexthink SA
Your question is too general.
goto keyword exist in C/C++ but its usage is not recommended at all as part of the practice modern programming techniques. Revise your program to avoid any goto in it.
 

Popular answers (1)

6th Mar, 2014
Heiko Rudolph
RMIT University
not making any assumption about your programming, skill or experience at all:
- why is GOTO not "efficient " in what way ? in what terms ??
this below is from my lecture about GOTO statements - taken directly from my notes, as is, -
Using the goto Statement
The goto is C++’s unconditional jump statement.
Label:
Statements;
goto label;
the label can be any valid C++ identifier and can be anywhere in the same function block as the goto.
listing 34
x = 1;
loop1:
x++;
if(x < 100) goto loop1;
A for loop can be written using a label and a goto.
Using more than one or two goto’s can easily circumvent the benefits of structured programming and OOP.
Too many Jumps and labels criss-crossing each other can make a program into a confusing mess and impossible to debug. The goto can easily be misused to create quick and dirty code that usually degenerates into chaos very quickly.
Therefore the goto fell out of favour with professional programmers because it encouraged the use of “spaghetti code”, code that was virtually unreadable.
Unfortunately the allure of goto is particularly strong for beginning programmers to whom using goto’s may see like a convenient and simple solution. Professionals will rarely if ever use it.
C++ could very well exist without the goto, in other words there is no situation in which a goto is absolutely essential.
Despite the above disclaimers there are situations where a goto is the most elegant and simplest solution.
The goto can clarify program execution if used wisely.
One such case is to use the goto to exit from a deeply nested routine.
The example below illustrates this:
listing 35 // using goto to exit from deeply nested loops
for(...) {
for(...) {
while(...) {
if(...) goto stop;
.
.
.
}
}
}
stop:
cout << "Error in program.\n";
Could a break have been used in place of the goto ?
Without the goto a number of additional tests and extra variables would be required.
NOTE: a goto cannot be used to jump from one function block to another, it is only valid within the block in which its label exists.
3 Recommendations

All Answers (8)

6th Mar, 2014
Zhang Shengdong
National University of Defense Technology
Using conditional jump would be more readable, but less efficient
6th Mar, 2014
Heiko Rudolph
RMIT University
not making any assumption about your programming, skill or experience at all:
- why is GOTO not "efficient " in what way ? in what terms ??
this below is from my lecture about GOTO statements - taken directly from my notes, as is, -
Using the goto Statement
The goto is C++’s unconditional jump statement.
Label:
Statements;
goto label;
the label can be any valid C++ identifier and can be anywhere in the same function block as the goto.
listing 34
x = 1;
loop1:
x++;
if(x < 100) goto loop1;
A for loop can be written using a label and a goto.
Using more than one or two goto’s can easily circumvent the benefits of structured programming and OOP.
Too many Jumps and labels criss-crossing each other can make a program into a confusing mess and impossible to debug. The goto can easily be misused to create quick and dirty code that usually degenerates into chaos very quickly.
Therefore the goto fell out of favour with professional programmers because it encouraged the use of “spaghetti code”, code that was virtually unreadable.
Unfortunately the allure of goto is particularly strong for beginning programmers to whom using goto’s may see like a convenient and simple solution. Professionals will rarely if ever use it.
C++ could very well exist without the goto, in other words there is no situation in which a goto is absolutely essential.
Despite the above disclaimers there are situations where a goto is the most elegant and simplest solution.
The goto can clarify program execution if used wisely.
One such case is to use the goto to exit from a deeply nested routine.
The example below illustrates this:
listing 35 // using goto to exit from deeply nested loops
for(...) {
for(...) {
while(...) {
if(...) goto stop;
.
.
.
}
}
}
stop:
cout << "Error in program.\n";
Could a break have been used in place of the goto ?
Without the goto a number of additional tests and extra variables would be required.
NOTE: a goto cannot be used to jump from one function block to another, it is only valid within the block in which its label exists.
3 Recommendations
7th Mar, 2014
Muhammad Ahsan
National University of Sciences and Technology
Thank You so much Mr. Heiko Rudolph. Nice explanation.
7th Mar, 2014
Simon Schröder
delta h
Muhammad, it is very complicated to answer your question. It depends on the exact problem that your are trying to solve by a goto statement. From the early days of programming (i.e. assembler programming) the replacement for goto directives is so-called structured programming. This means using if-then-else statements, for- and while-loops, switch statements, break and continue, etc. Also with all modern optimizing compilers using functions can be a way to circumvent some goto statements and still have readable code.
If you can provide a short example, maybe an experienced C++ programmer could tell you how he would write it differently without a goto statement. I have been writing C++ code for almost 15 years now. And I never needed to use a goto statement.
Since you mentioned that you have problems with memory management you should have a look at the RAII concept (Runtime Allocation Is Initialization). This puts allocation into constructors and deallocation into destructors. A good overview of best practices for C++ programming (including RAII) can be found in the book "Effective C++" by Scott Meyers. If you want to avoid memory management problems, don't use new and delete inside functions if you don't have to. Most of the time an object on the stack is all you need. Constructors and destructors are good places where you can put new and delete (which is related to RAII).
2 Recommendations
7th Mar, 2014
Tillmann Nett
FernUniversität in Hagen
The goto statement fell very much from grace due to dijkstras essay "Go To Statement Considered Harmful" (http://www.u.arizona.edu/~rubinson/copyright_violations/Go_To_Considered_Harmful.html).
However when obeying a few rules, a goto is often pretty usefull and not at all bad programming. E.g. the Linux kernel is sometimes considered one of the cleanest projects (at least when leaving out staging drivers and experimental portions), and it used goto a lot. The main rules for using goto are:
1. Only jump locally, i.e. to a code that is near the one you are jumping from. Never jump to another function or into another file (I am not sure wether this would even work, but I am afraid it might compile).
2. Only jump forward, never backward.
3. Only use gotos for exceptional circumstances
In the linux kernel this usually looks like this
int retval;
resource * r1 = get_some_resource();
if( r1 == NULL ) {
retval = some_failure1;
goto fail;
}
resource * r2 = get_some_other_resource();
if( r2 == NULL ) {
retval = some_failure2;
goto fail_with_r1;
}
...
fail_with_r1:
cleanup_resource( r1 );
fail:
return retval;
This code is quite easy to understand and does not produce any spaghetti. Jumps are confined to the same function, and only go to the end of the function for error handling, so there are hardly any problems with that.
If you have more than two resources however this pattern gets out of hand quickly. Also this is the C way of doing things and C and C++ are two completly different things.
The same thing in C++ would usually be handled using RAII (the cleanup then happens in the destructor) and by throwing exceptions. If done correctly, this also has the benefit of making it completly impossible to forget about resource cleanup (even better than with a GC). So most jumps in C++ are handled using exceptions, which also indicates, that these jumps only happen in exceptional circumstances.
2 Recommendations
30th Mar, 2014
Francisco Inacio
University of Hull
Heiko already explained most of what I wanted to say, but generally I would say not to use goto statements at all in your code, even if that means adding a bit more lines. As Simon pointed out, it is hard to answer your question because there are many different situations where you could replace goto statements and it really depends on what you are trying to do. I suggest posting your code in a forum or as a stackoverflow question, where people can help you looking for alternatives and even explain the changes they have made to your code.
31st May, 2015
Tetyana Sopronyuk
Chernivtsi National University
In other situations:
break;
continue;
condition in loop;
return;
exit
9th Aug, 2015
Hossein Afshari
Nexthink SA
Your question is too general.
goto keyword exist in C/C++ but its usage is not recommended at all as part of the practice modern programming techniques. Revise your program to avoid any goto in it.
 

Similar questions and discussions

Related Publications

Book
The TEL (Technology Enhanced Learning) Series on Software Development is a multi-volume set of lecture notes for students learning how to program modern computers. This second volume introduces object-oriented programming concepts using the most recent standard of the C++ language. Object-oriented programming is widely used in the design of many la...
Book
2nd Volume in the TEL Series on Software Development: The TEL (Technology Enhanced Learning) Series on Software Development is a multi-volume set of lecture notes for students learning how to program modern computers. This second volume introduces object-oriented programming concepts using the most recent standard of the C++ language. Object-orie...
Article
Reusability is one in every of most vital advantage of C++ programming language. C++ categories are often reused in many ways in which. Once the parent (Base) category has been written it are often changed by another technologist to suit their needs. the most plan of inheritance is making new categories, reusing the properties of the present base c...
Got a technical question?
Get high-quality answers from experts.