Sign in to follow this  
armitroner

C++ - Is Goto a Good Practice?

Recommended Posts

armitroner    132
I've made a simple little text-based game that implements an extremely primitive menu. For it, I have designed a small option menu for attacks. Before, it used to automatically move on to the opponent's attack if you happened to use the gun attack if you were out of ammo, so I fixed that by adding a goto function that reverts back to the option menu before the enemy initiates it's attack.

I've read in some places that goto is unreliable, and indeed, shouldn't be used in most cases. I was just curious as to specifically why this is, and what alternative could I use?

Share this post


Link to post
Share on other sites
armitroner    132
Oh, yeah, sorry!
I only used goto in one small section, since I don't have much need for it elsewhere.

[source lang="cpp"]void Combat::combatChoice(Character& C) {
if (C.health < 0 || C.health == 0) {
cout << "----------------- You died... ------------------" << endl;
cout << "Oh dear, it seems you have died... Game Over." << endl;
} else {
battlemenu:
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;
switch (choice) {
case 1:
cout << "\n----------------- Battle Results ------------------" << endl;
C.meleeAttack(M);
break;

case 2:
cout << "\n----------------- Battle Results ------------------" << endl;
if(C.ammo == 0) {
cout << "You're out of ammo! \n" << endl;
goto battlemenu;
} else {
C.gunAttack(M);
}
break;

case 3:
cout << "\n----------------- Battle Results ------------------" << endl;
if(C.potions == 0) {
cout << "You're out of potions! \n" << endl;
goto battlemenu;
} else {
C.useHP(C);
}
break;
}
}
}[/source]

Share this post


Link to post
Share on other sites
armitroner    132
[quote name='TheChubu' timestamp='1352681646' post='5000061'] You could implement your battlemenu separately and make a call to it when you need it instead of using goto. The thing about goto is that you basically get rid of every pre/post condition that a block of code should have. When you have an if else block that, besides having the two normal possible outcomes (if branch or else branch), jumps to another place with a goto in the middle, then nothing is safe anymore. You stomp over every "safety" that basic control structures should give to you when using goto to reach some place in the code. Its like having a carefully designed brake system in a car, only to go and smash it against a wall because you think you can stop the car faster by doing so. [/quote]

[quote name='superman3275' timestamp='1352681863' post='5000063'] Goto can also make spaghetti code. A lot of times what ends up happening is that your code is jumping from place to place, making it extremely hard for other people to understand what you're doing. It also makes it hard for you. (Example: Code an awesome enemy system. A month later you need to extend it. Go to look at it and it keeps on jumping to a bunch of places, and you don't understand it, so you scrap all your code.). Now, GoTo isn't always evil. There's an application for everything. However generally using Goto is frowned upon, and the problem you're solving with it can be solved by using object oriented programming. [/quote]

I see. So basically, goto is really only a last-ditch alternative for when you don't need to go back and extend it all that much. The better thing to do would be to create a separate class specifically for the battle menu? Crap, another class I have to make... :P

Anyhow, thanks! I'll see how I can change it to a class, though I'm still not entirely sure how to split all the options into a class, so maybe I could get a couple pointers here?

Share this post


Link to post
Share on other sites
Bregma    9202
The posted code is precisely the sort of code Edsger Dijkstra was referring to in his famous letter to CACM titled "GOTO Considered Harmful." It's what we used to refer to as "spaghetti code." In this example it's on a small scale, but spaghetti code nevertheless. The stuff as dreams (bad ones) are made on.

When I started programming, that's pretty much the way all code was written. The available languages gave you little choice.

I'm not averse to using goto in code, especially if you're stuck with a primitive language like assembler, FORTRAN IV, or C (I've used goto in all of those). Even in C, the use of goto should really be limited to forward jumps for error paths (to effectively unwind the stack) and not as a general looping control construct as seen here.

Modern languages such as C++ have no need for goto at all. If you structure your logic correctly your code will be far far easier to read, maintain, extend, and explain all without a hint of pasta. Edited by Bregma

Share this post


Link to post
Share on other sites
Peter Dreyer    108
Stay away from the evil goto statement in C++. it may seem nice until your project gets larger at which point they'll help to create 'spaghetti code'. C++ is made so that you don't have to use them. The only time you should need to use goto statements in in Assembly. Edited by petrusd987

Share this post


Link to post
Share on other sites
Sparkon    579
IMHO the goto statement should not be used, but there are some few exceptional cases, for example if you are inside a nested-nested-nested loop than you might use it. There are other ways though ( better in my opinion ) .

I link you this [url]http://www.u.arizona.edu/~rubinson/copyright_violations/Go_To_Considered_Harmful.html[/url] that was written by dijkstra about the use of GOTO statement. It's a good read!

Share this post


Link to post
Share on other sites
apatriarca    2365
[font=arial,helvetica,sans-serif]This is not really related to your question, but I think you may be interested to recieve other feedbacks on your code.[/font]

[source lang="cpp"]C.health < 0 || C.health == 0[/source]
The code above is equivalent to
[source lang="java"]C.health <= 0[/source]
What's M in your code? You have used it, but it is not declared in the function. If it is some kind of global or member function I think you should probably use a more descriptive name.

Share this post


Link to post
Share on other sites
Bacterius    13165
Also, please put brackets around logical conditions!
[source lang="cpp"]((a < 0) || (b == 0))[/source]
Yes, I know, operator precedence generally plays in your favor, but it just feels so much more readable to me (provided you don't end up with five or six nested parentheses, but in that case you probably should simplify the condition anyway). It's more a matter of personal taste, thus subjective, but I thought I'd throw it out there.

Share this post


Link to post
Share on other sites
lauris71    841
If you are posting in beginners forum then you shouldn't use goto in your code [img]http://public.gamedev.net//public/style_emoticons/default/wink.png[/img]
Once you reach advanced level... well, then you know yourself.

Share this post


Link to post
Share on other sites
blutzeit    1650
[quote name='Lauris Kaplinski' timestamp='1352720812' post='5000200']
If you are posting in beginners forum then you shouldn't use goto in your code [img]http://public.gamedev.net//public/style_emoticons/default/wink.png[/img]
Once you reach advanced level... well, then you know yourself.
[/quote]

...then you'll rather use comefrom ([url="http://en.wikipedia.org/wiki/Comefrom"]http://en.wikipedia.org/wiki/Comefrom[/url])

Share this post


Link to post
Share on other sites
armitroner    132
[quote name='rip-off' timestamp='1352715500' post='5000174']
[quote]
I only used goto in one small section, since I don't have much need for it elsewhere.
[/quote]
You are essentially abusing goto to create a loop. Instead, use an explicit loop:
[code]
...
[/code]
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:
[code]
...
[/code]
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. [img]http://public.gamedev.net//public/style_emoticons/default/tongue.png[/img]
Anyhow, thanks for the advice, and I'll be working on improving my code once my compiler gets fixed... [img]http://public.gamedev.net//public/style_emoticons/default/happy.png[/img]

Share this post


Link to post
Share on other sites
DracoLacertae    518
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.

Share this post


Link to post
Share on other sites
dmatter    4826
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&amp;amp; 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). Edited by dmatter

Share this post


Link to post
Share on other sites
Vilem Otte    2938
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. [img]http://public.gamedev.net//public/style_emoticons/default/smile.png[/img]

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this