C++ - Is Goto a Good Practice?

Started by
45 comments, last by SiCrane 11 years, 5 months ago


I only used goto in one small section, since I don't have much need for it elsewhere.

You are essentially abusing goto to create a loop. Instead, use an explicit loop:

...

Note that this automatically handles the case where the user types an invalid option by looping around, though it is generally nicer to print a specific message in this case.

Another potential improvement is to dynamically remove invalid options from the menu. Something like this:

...

I'm not sure if you are familiar with std::vector or function pointers. Feel free to ask a question if you don't understand what this code is doing.
[/quote]

From what I can see in the second example, it's working sort of like an array. It appears to be creating a single, erm, (for lack of a better term) method that carries the other functions in it, kinda like how a class works? Then it grabs how many functions are underneath CombatChoice and displays them, dependent upon wether or not they meet the conditions given when using the push_back function. (not sure what push_back is)
Finally, when choosing the option, the reason you created that variable when creating the menu was to add an extra bumper in case the player chose the number of an option that wasn't even there.

I'll do a bit of reading on std::vector, since this is the first time I've come across the term. This was actually my first serious C++ project, so I had to hunt down tons of stuff on the net. tongue.png
Anyhow, thanks for the advice, and I'll be working on improving my code once my compiler gets fixed... happy.png
Advertisement
Goto still exists for a reason. At work, we have a large C codebase that has a few goto's in it. It's used as 'goto cleanup', to bail-out of a function, but allow for freeing objects. In C++ you would use an exception or just let the destructors do their job, in C there is no such luxury. You might also be able to make a case for using it in a C++ program if you need to manually free something that doesn't have a destructor ( maybe you were interfacing to something written in plain C), but you would probably want to wrap your C structs into a C++ object with a proper destructor instead.

I do see this sometimes, and I think this construct is worse than a goto:
[source lang="C++"]
do {

stuff;
if (!stuff)
break; //really just a 'goto' in disguise
stuff;
if (oh_crap)
break; //another goto

for (i=0;xxx;xxx)
{
if (whatever(i))
{
outer_break=true;
break;
}
}
if (outer_break)
break; // well wasn't that awkward

stuff;

} while (0);

free(things);
[/source]
As you can see above, break is really just as bad as goto, and if you need to break from inside an inner loop, it gets awkward.

The other acceptable use I see for goto are the gcc extenstion of 'computed gotos' where you can have label pointers, and build a jump table. This is handy if you are writing a bytecode interpreter, BUT is really just the same thing as the jump table that a good compiler is supposed to try to make for a switch/case statement.

Other than these two cases, goto is almost always a mistake.
Obligatory XKCD.

goto.png
As far as I know there is no case where a goto in C++ is the best tool for the job. I have never had cause to use it in C++ and I would not be overly happy to read or maintain code that uses it either.

Goto has a couple of uses, chiefly amongst them is making loops and exiting out of nested code. Instead it's better to prefer explicit loops and factoring nested code into functions which can be exited using return.

I combination of these alternatives can be applied to your function, including some minor restructuring that makes it a little cleaner:

[source]
void Combat::combatChoice(Character& C) {
if (C.health <= 0) {
cout << "----------------- You died... ------------------" << endl;
cout << "Oh dear, it seems you have died... Game Over." << endl;
return;
}

for (;;) {
cout << "----------------- Battle Options ------------------" << endl;
C.Display();
cout << "What do you want to do? \n"
<< "Type the number of the action and press enter. \n"
<< "[1] Melee Attack \n"
<< "[2] Gun Attack \n"
<< "[3] Health Potion" << endl;

short choice;
cin >> choice;

cout << "\n----------------- Battle Results ------------------" << endl;
switch (choice) {
case 1:
C.meleeAttack(M);
return;

case 2:
if(C.ammo > 0) {
C.gunAttack(M);
return;
}

cout << "You're out of ammo! \n" << endl;
break;

case 3:
if(C.potions > 0) {
C.useHP();
return;
}

cout << "You're out of potions! \n" << endl;
break;

default:
cout << "Whoops you choose an incorrect battle option, try again!\n\n";
}
}
}[/source]

So we've used an infinite loop which is basically saying "keep going till the user provides us with a workable option" (and such a thing would make a good code comment above the loop). Once a valid option has succeeded it exits from the function entirely using mid-function returns.

I find mid-function/early returns are often easier and clearer than using control variables to guide execution out of loops toward the end of a function. There are cases to be made either way.

I think rip-off's second example is better factored, more extensible and offers a superior experience for the user. An observation off the back of it is that having battle actions as member functions on a Character is slightly awkward as it involves a second abstraction for unifying the interface to them: f(C, M)
It may make sense to separate the action concept out as a first-class citizen, e.g. MeleeAttack::apply(Character & C, Monster & M);
Then just register all your Attack actions into the menu vector. You could add other member functions, such as one that predicates whether the action is even valid on the current menu (otherwise the menu code has to know something about what each attack requires).
I actually used goto once or twice in C to decrease number of nested loops in code (it made code look a bit better)... I could've used function there though, but I didn't want (separating that code would be a hell for anyone who would read it).

Basically if you are beginner (and assuming that, because this is in forums For Begginers), you shouldn't use it at all. smile.png

My current blog on programming, linux and stuff - http://gameprogrammerdiary.blogspot.com

goto is not evil in and of itself. There are some very rare occasions when a carefully placed goto can save you a lot of time.

The problem is that goto is essentially an intrinsic for the 'jmp' instruction. If you're good with assembly and understand stack frames and the general behavior of the compiler then you can get away with it, but otherwise just do whatever you have to do to avoid it. The risk of unexpectedly dragging invalid state into somewhere that it doesn't belong (and not having the correct state established for that location) is simply too great.

Even if you do have a perfect grasp of the mechanics and implement a correct use of goto then you'll probably only do it either as a temporary measure or else as some form of bizarre optimization accompanied by 3 pages of commenting.
void hurrrrrrrr() {__asm sub [ebp+4],5;}

There are ten kinds of people in this world: those who understand binary and those who don't.
If goto would be that bad it wouldnt exist. Its better not to use it for jumping through long code though .....especially if many people are working on the same code.
+(Ive worked at 2 big companies ....neither allowed to use goto:))
Aliii: Some things exist as an evil legacy from the dark times.

As far as I know there is no case where a goto in C++ is the best tool for the job.

The only thing I can think of is for the output of automatic code generators such as lexers and parsers. It produces unmaintainable spaghetti code, but it doesn't matter because it's not meant to be maintained by human hands.
Basically there's no reason to use "goto" unless your code's workflow is incorrect.

This topic is closed to new replies.

Advertisement