Why and when should a goto be used in C / C++? [duplicate] - c++

This question already has answers here:
Examples of good gotos in C or C++ [closed]
(16 answers)
Closed 9 years ago.
I know lots of questions about why not use goto, why goto is bad practice, why goto was create by devil, why the fingers of those who type goto should be ripped off, etc...
And in many answers to this questions , this question, and even at wikipedia it's possible to find reasons pro / against goto.
Even Stackoverflow has a goto tag :)
But, obviously, goto is accepted as a valid command, otherwise your compiler / interpreter wouldn't know what to do with it. Even in C / C++ it's possible to use goto, and that language even has a formal, ISO specification.
So, probably, there should be some case where only by using goto it's possible to accomplish some task. Then, why and when should a goto be used in C / C++ ?
Edit:
Just to make sure:
1 - this question doesn't require debate. It should be answerable: giving one or more cases where goto is the only solution, or stating no, it's always possible to avoid a goto. Of course, I'm not the only who can decide whether it should be closed or not, but I don't think that "too broad, asks for debate, etc" are reasons to close it.
2 - There might be some cases where goto make the code cleaner, faster, etc. I don't want those. I want to know if there exists one case where goto is the only solution (no, it's not a dup of that "give good examples of goto" question)
3 - I'll accept any downvote, with a smile on my face, if the downvote is justified. But I'm pretty sure that this question has an answer and has done previous research about the subject. Downvoting simple because those 4-letters taboo word that starts with a "G" was used... sorry...

There is no circumstance under which a goto is strictly necessary: you can always avoid it if you really want to, but to do that for purely idealogical reasons is a mistake.
For example, a friend of mine wrote a wavelet transform function that had (something like) 15 nested loops. In the event of an error in those loops, he had a goto to a cleanup block just before the function's return statement. To achieve the same effect without a goto would have involved setting a flag and testing it at every loop level, which would have made his code far less readable. In these circumstances, goto was the right choice.

The latest MISRA standard now allows gotos.
A good example where gotos make sense is when you have a large routine with a lot of exits points. You can have many return statements (not good) convolute the code with 'structured programming' conditionals (also not good) or a "goto Done; which sends the program to a set of ending statements before returning.
The MISRA standard basically allows gotos for these sort of circumstances. I think 'only downward' is one of their criteria.

The only reason I use a goto is when it is for an error return condition from a function that needs some common cleanup. The target of the goto is near the end of the function and the "normal" return returns before the label.

Here is an example where only goto will work:
https://stackoverflow.com/a/245801/193848
Basically if you have multiple nested for loops, the only way to break out of all the loops from an inner loop is with a goto statement (since unlike some other languages the C break keyword doesn't support a parameter for the number of nesting levels to break out).

Related

Is returning a functions value from a for-loop bad practice in C++? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 6 years ago.
Improve this question
My colleague just had a look at my code and said, that according to "some standard" returning a functions value out of a for loop is bad practice.
The function looks something like this:
bool CentralWidget::isBitFieldFree(const QString& define, int lsb, int msb)
{
QString defineWithoutIndex = getDefineWithoutIndex(define);
for (int i = lsb; i <= msb; i++)
{
if ((registerBitMap[defineWithoutIndex] >> i) & 1)
return false; //Returning here early...
else
registerBitMap[defineWithoutIndex] |= 1 << i;
}
return true;
}
Questions:
Is there a a standard that bans this?
is this concidered bad practice?
if so: why?
There is no such standard as this in the world of c++. However in a more specific environment (such as a company), specialized standards might apply.
With that said, it's not bad practice, in general.
a) a standard that bans this?
No.
b) is this concidered bad practice?
No.
c) question is already answered.
Other than that, it lies under the scope of personal preference, and here is mine - but this obviously not a part of a real answer:
You want to return true, after you have looped over your string, so how could you do it elegantly inside the loop? With an if statement saying that if it's the last iteration, return true, at the end of the loop?
I think this puts more lines of code in your file, without any reason, and damaging severely the readability.
There is a school of thought that says that a function should have a single entry and a single exit point. That makes some static analysis of the code easier, but in C++ very likely serves no other purpose.
This kind of thinking comes mostly from C, where it can make a lot of sense to exit the function trough a single point to ensure resources eventually taken by the function are properly cleaned up on exit. Replicating this cleanup across multiple exits is considered to be brittle and hard to maintain - I agree.
In C++ however the preferred way to control your resources is through RAII or by using RAII-classes like shared pointers, string and vector. Thus the amount of code required to clean up resources on exit is often null, because it is implicitly done in the destructors of the objects in the local scope. Therefor it usually does not make any sense to enforce single-entry/single-exit unless you have a good reason to do so.
In some coding standards you could find things like 'a function should have only one exit point'. Often this was related to cleanup procedures, but in the days of smart pointers this does not apply anymore.
So, as the other answers and comments say: No, there is no such standard.
Also, I don't think it's bad practice.
Even more: I would say you don't need the 'else', because if you exit the loop/function, processing only continues in the 'else' case. Does not matter much in your case, but if you have multiple ifs, it can save you a lot of nesting.
There can be different opinion on this and people may argue it makes an "unintuitive" control flow. But there is no standard for this.
Personally I find this a better practice than having an extra variable and condition to exit the code. You want to leave the scope at this point and you do this by returning from the function. I sometimes even put code in an extra function just to be able to use the feature of leaving the scope from anywhere with a return.
This also has the advantage of creating less lines of code. And less lines of code are less opportunities to introduce a bug.

What to use instead of Goto Statements? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
I'm wondering what I should be using instead of goto statements?
Should I be using nested if/while/do-while statements?
They say that using goto creates 'spaghetti code', but surely if someone is writing a large console application and they have if statement after if statement in an attempt to control the flow, that's going to make a mess?
I'm asking as many people have asked why the goto statement is bad, but not what to replace it with. I'm sure a lot of beginners could do with this.
This is for C++.
You are much better off using functions, loops, and conditional statements. Use break and continue as necessary.
I can nearly guarantee you any situation in which you are utilizing goto there is a better alternative. There is one notable exception to this: multi-level break.
while(1){
while(1){
goto breakOut;
}
//more code here?
}
breakOut:
In this one (relatively) rare situation, goto can be used in place of a typical "break" to make it clear we are actually getting out of a nested loop. The other way to approach this is with a "done" variable:
while(!done){
while(!done){
done = true;
break;
}
if(done){break;}
//More code here? If so, the above line is important!
}
As you can see, the done variable is more verbose when you have additional processing in outer loops, so a goto is a cleaner way of breaking free!
However, in 99% of cases you really, really, don't want to start writing a bunch of goto statements. Really think through each one.
With functions the above could also be written like so:
bool innerLoop(){
while(1){
return false;
}
return true;
}
...
while(innerLoop()){ //can only be written this way if the inner loop is the first thing that should run.
//More code here?
}
...
Sometimes breaking an inner loop out in this way can be messy if there are a lot of dependencies on the outer one. But it remains a viable way of breaking out of code early with return statements instead of goto or break.
If you can write your logic using a clean, modern construct, then use it. Otherwise, if goto makes sense, use it.
In general, goto can make your code harder to read and follow the flow of the code. For that reason, newbies are told to avoid goto altogether. This encourages them to think in terms of other constructs.
But some people just get religious about it. Coding is not a religion. And if a goto makes sense, C++ has a perfectly valid goto statement and you should use it when it makes good sense.
It doesn't make sense to me to ask what you should use instead of goto. You can generally use some type of loop or other construct, depending on what you are doing. But where goto makes sense, use it.
Don’t listen to people who say "never use goto". You're quite right that there are cases where nesting scoped blocks will make a heck of a lot more mess than a goto. It has its place, just as a switch/case does. However, with functions you can often refactor away the entire argument and keep people happy.
Simply forget that there is the goto statement in C++ and there will not be questions about how to replace the goto.:)
As for me I never see a code with goto statement that I could call it as a good code. Usually a goto statement is the source of some kind of errors and difficulties. Especially it is difficult to modify such code. Moreover one goto statement usually starts to produce other goto statements in the code.:)
The goto is bad because it allows you to jump from context to context. The context is a vector of all your variables (with their values) at a particular point of your program. A program execution graph shows you how your program jumps from context to context. It's in your best interests to keep the execution graph as simple as possible. The simplest one is a chain, the next step is an execution tree. A loop adds complexity, but it's a managed complexity. If you have a node in your execution graph, which is reachable via more than one execution path, and you need to understand a context at this node, then you'll need to follow more than one execution path back. These "merge" nodes add a lot to the complexity of your program. Each labeled statement (the goto target) is a potential merge node.
So, try don't use the goto operator at all - the language itself will force you to find a manageable solution using loops, boolean variables, classes, functions etc. and your program will be more clear and understandable. C++ exceptions is another manageable way to jump between contexts.
There are computing geniuses, who can keep in their minds and process very complex execution graphs, so they don't care much about complexity of their programs or a next programmer, who will be assigned to support or take over their code in the future. I guess, we have some of them here :-)

Are goto statements efficient when compared to calling functions? [closed]

As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 10 years ago.
I have the following code in C++ here:
#include <iostream>
int main(int argc, const char * argv[])
{
goto line2;
line1:
std::cout << "line 1";
goto line3;
line2:
std::cout << "line 2";
goto line1;
line3:
std::cout << "line 3";
goto line4;
line4:
std::cout << "Hello, World!\n";
return 0;
}
If I made a larger program of lets say 10,000 lines of code and I decide I am never going to use functions that I write myself, I only use goto statements. I only use global variables. I am slightly insane in terms of best practices, but its for a very specific purpose. The question is, would this be efficient to jump around with goto statements? What if I have 1000 goto labels?
Do the goto statements translate directly into machine code which tells the computer just to JUMP to a different memory address? Is this a lower cost in the machine to jump around like this when compared with the cost to call a function?
I wish to know as I want to write a very efficient program to do some computations and I need to be very efficient without resorting to Assembly/Machine code.
No need to tell me this is a bad idea in terms of maintenance, understandability of code, best practices, I'm very aware of that, I just wish to have an answer to the question. I don't want any debate between whether its good to use function calls or good to use goto.
To clarify the question, I am concerned in this case of using gotos only with a 10,000 line program as to how it would compare with a traditional program using functions. There are multiple ways to compare and contrast between these two programs, for example how would the CPU cache perform. What sort of saving would it give without function calls. Without a call stack, how would this impact on the CPU cache, as CPU caches usually keep the stack close. Would there be therefor a case where it is likely to have a negative performance hit due to the cache not being utilized correctly. What is the actual cost of calling a function as compared to a jump in terms of time efficiency. There's a lot of ways to compare and contrast the two styles of programming in terms of efficiency.
Do the goto statements translate directly into machine code which tells the computer just to JUMP to a different memory address?
Yes.
Is this a lower cost in the machine to jump around like this when compared with the cost to call a function?
Yes.
However, when the compiler sees a function call, it doesn't have to actually generate code to call a function. It can take the guts of the function and stick them right in where the call was, not even a jump. So it could be more efficient to call a function!
Additionally, the smaller your code, the more efficient it will be (generally speaking), since it is more likely to fit in the CPU cache. The compiler can see this, and can determine when a function is small and it's better to inline it, or when it's big and better to separate it and make it a real function, to generate the fastest code (if you have it set to generate the fastest code possible). You can't see this, so you guess and probably guess wrong.
And those are just some of the obvious ones. There are so many other optimisations a compiler can do. Let the compiler decide. it's smarter than you. It's smarter than me. The compiler knows all. Seriously, Cthulhu is probably a compiler.
You said not to, but I'm going to say it: I highly advise you to profile your code before deciding to do this, I can almost guarantee it's not worth your time. The compiler (most of which are near-AI level smart) can probably generate as fast or faster code with regular function calls, not to mention the maintenance aspect.
Do the goto statements translate directly into machine code which
tells the computer just to JUMP to a different memory address?
Pretty much.
Is this a lower cost in the machine to jump around like this when
compared with the cost to call a function?
A function call is going to make a pretty similar jump, but before you can make the jump, you have to set up the new stack frame for the new function, push on parameters according to calling conventions, and at the end set up any return value and unwind. Yes, it's probably faster to not do this.
I am slightly insane
Yes.
1) The question is, would this be efficient to jump around with goto statements? What if I have 1000 goto labels?
From your small example with 4 goto labels, where you jump back and forth, no it is not efficient in terms of performance. To avoid overhead in function call mechanism, this method is disabling many other optimization which the compiler will automatically do for you. I am not listing them, but this worth reading.
2) Do the goto statements translate directly into machine code which tells the computer just to JUMP to a different memory address?
YES (As others correctly pointed out)
3) Is this a lower cost in the machine to jump around like this when compared with the cost to call a function?
YES, only if your compiler is pre historic, and doesn't have any optimization mechanism in built. Otherwise NO.
And I am not talking about best practices..
Yes, the machine code generated from goto will be a straight JUMP. And this will probably be faster than a function call, because nothing has to be done to the stack (although a call without any variables to pass will be optimized in such a way that it might be just as fast).
And God help you when something doesn't work with this code. Or when someone else has to maintain it.
hard to answer your query precisely, it depends on complexity of your program and use of goto statements within.
goto statement is equivalent to unconditional jump instruction (e.g. jmp ). The scope of goto will be within the file.
Ritchie suggest that avoid using goto statement, and if still want to/have to use goto statement then use it in top-down approach, Dont use it in bottom-up approach.
Well these are text book details.
Practically you should be very sure where to use goto statement and after goto jump where your program flow will be, otherwise as you mentioned with 1000 goto statements it will be difficult for you also to decide the program flow, forget about others. So further improvement in your program will be very very difficult.
There are plenty of other facilities such as looping, conditional statements, break and continue statements, functions etc to help you avoid such problems.
Hope it helps.....
In short, 'GoTo' statements can be efficient, but that is really how they are used. According to Herbert Schildt (C++ from the GROUND UP), "There are no programming situations that require the use of the goto statement -- it is not an item necessary for making the language complete." Ultimately, the primary reason for many programmers disliking the statement is that goto statements tend to clutter your code and/or make it very difficult to read because, as per the name, gotos can jump from place to place. With that being said, there are times where a goto statement can reduce clutter as well as make code more efficient, but that is totally dependent upon how you use them and the context that they are used in. Personally, I would recommend using function calls, as oppose to several goto statements; others may disagree.

Why choosing for (;;){} over while(1)? [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Is “for(;;)” faster than “while (TRUE)”? If not, why do people use it?
I see this
for (;;)
{
// Some code here
}
quite often. But what benefits does it offer and why just not choose while(1){}?
They produce identical code. There are a couple of reasons why you might prefer for (;;) but it is all just personal preference:
Some compilers will warn you about conditions that are always true. for(;;) will not have that problem.
for (;;) literally reads as "Just loop forever!", whereas while (true) still appears to have some kind of condition.
I say pick one and stick with it. It doesn't matter as long as you don't switch between them arbitrarily.
This is the form of the forever loop that Kernighan and Ritchie used in their book*. There is absolutely no other reason to prefer one form over the other.
* Section 3.5 on While and For loops, example number four.
The two are equivalent and will most likely result in identical machine code. Choosing one over the other is a matter of personal preference.
It does not really matter - it is just personal preference.
I like for(;;) better because I think it underlines loop forever aspect.

What is wrong with using goto? [duplicate]

This question already has answers here:
Closed 12 years ago.
Possible Duplicates:
Why is it bad to use goto?
GOTO still considered harmful?
I was ramdomming through xkcd and saw this one (if also read some negative texts about them some years ago):
What is actually wrong with it? Why are goto's even possible in C++ then?
Why should I not use them?
Because they lead to spaghetti code.
In the past, programming languages didn't have while loops, if statements, etc., and programmers used goto to make up the logic of their programs. It lead to an unmaintainable mess.
That's why the CS gods created methods, conditionals and loops. Structured programming was a revolution at the time.
gotos are appropriate in a few places, such as for jumping out of nested loops.
Nothing is wrong with goto if it is used properly. The reason it is "taboo" is because in the early days of C, programmers (often coming from an assembly background) would use goto to create incredibly hard-to-understand code.
Most of the time, you can live without goto and be fine. There are a few instances, however, where goto can be useful. The prime example is a case like:
for (i = 0; i < 1000; i++) {
for (j = 0; j < 1000; j++) {
for (k = 0; k < 1000; k++) {
...
if (condition)
goto break_out;
....
}
}
}
break_out:
Using a goto to jump out of a deeply-nested loop can often be cleaner than using a condition variable and checking it on every level.
Using goto to implement subroutines is the main way it is abused. This creates so-called "spaghetti code" that is unnecessarily difficult to read and maintain.
There is nothing wrong with goto in itself. It's a very useful construct in programming and has many valid uses. The best that comes to mind is structured resource freeing in C programs.
Where goto's go wrong is when they are abused. Abuse of gotos can lead to thoroughly unreadable and unmaintainable code.
In 1968, Edsger Dijkstra wrote a famous letter to the editor of Communications of the ACM GOTO is considered harmful in which he laid out the case for structured programming with while loops and if...then...else conditionals. When GOTO is used to substitute for these control structures, the result is very often spaghetti code. Pretty much every programming language in use to day is a structured programming language, and use of GOTOs has been pretty much eliminated. In fact, Java, Scala, Ruby, and Python don't have a goto command at all.
C, C++ and Perl still do have a GOTO command, and there are situations (in C particularly) where a GOTO is useful, for example a break statement that exits multiple loops, or as a way of concentrating cleanup code in a single place in a function even when there are multiple ways to terminate the function (e.g. by returning error codes at multiple points in the progress of a function). But generally its use should be restricted to specific design patterns that call for it in a controlled and recognized way.
(In C++, it's better to use RAII or a ScopeGuard (more) instead of using GOTO for cleanup. But GOTO is a frequently used idiom in the Linux kernel (another source) which is a great example of idiomatic C code.)
The XKCD comic is a joke on the question "Should GOTO always be considered harmful when there are certain specific design patterns that are helped greatly by its use?"
Did you google the issue?
The founder of the anti-goto movement is Edsger Dijskstra with his legendary "Goto Considered Harmful"
To get you started you can goto (ha ha!) http://en.wikipedia.org/wiki/GOTO
It's possible in C++ because it's possible in C. Whether you should or shouldn't use it is long-standing religious war.
It was a design goal of C++ that 99-point-something percent of C programs in the wild should compile and run with the same functionality in C++. Including goto was part of the effort to reach that goal.