Jump to content

  • Log In with Google      Sign In   
  • Create Account

C++ - Is Goto a Good Practice?


Old topic!
Guest, the last post of this topic is over 60 days old and at this point you may not reply in this topic. If you wish to continue this conversation start a new topic.

  • You cannot reply to this topic
46 replies to this topic

#1 armitroner   Members   -  Reputation: 132

Like
3Likes
Like

Posted 11 November 2012 - 06:31 PM

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?

Sponsor:

#2 Alpha_ProgDes   Crossbones+   -  Reputation: 4692

Like
1Likes
Like

Posted 11 November 2012 - 06:34 PM

If you posted the code you've implemented it'll be easier for people to give practical advice and coding tips, other than: "GOTO IZ EVIL!!!!111!!!!111!"
Beginner in Game Development? Read here.
 
Super Mario Bros clone tutorial written in XNA 4.0 [MonoGame, ANX, and MonoXNA] by Scott Haley
 
If you have found any of the posts helpful, please show your appreciation by clicking the up arrow on those posts Posted Image
 
Spoiler

#3 armitroner   Members   -  Reputation: 132

Like
0Likes
Like

Posted 11 November 2012 - 06:37 PM

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©; } break; } }}[/source]

#4 TheChubu   Crossbones+   -  Reputation: 4819

Like
9Likes
Like

Posted 11 November 2012 - 06:54 PM

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.

"I AM ZE EMPRAH OPENGL 3.3 THE CORE, I DEMAND FROM THEE ZE SHADERZ AND MATRIXEZ"

 

My journals: dustArtemis ECS framework and Making a Terrain Generator


#5 superman3275   Crossbones+   -  Reputation: 2061

Like
5Likes
Like

Posted 11 November 2012 - 06:57 PM

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.

I'm a game programmer and computer science ninja ph34r.png!

Here's my 2D RPG-Ish Platformer Programmed in Python + Pygame, with a Custom Level Editor and Rendering System!

 

Here's my Custom IDE / Debugger Programmed in Pure Python and Designed from the Ground Up for Programming Education!

Want to ask about Python, Flask, wxPython, Pygame, C++, HTML5, CSS3, Javascript, jQuery, C++, Vimscript, SFML 1.6 / 2.0, or anything else? Recruiting for a game development team and need a passionate programmer? Just want to talk about programming? Email me here:

hobohm.business@gmail.com

or Personal-Message me on here smile.png!


#6 irbaboon   Members   -  Reputation: 906

Like
10Likes
Like

Posted 11 November 2012 - 07:06 PM

Is goto a good practice?

Is synonymous with

Is jumping into a volcano a good idea?



#7 armitroner   Members   -  Reputation: 132

Like
0Likes
Like

Posted 11 November 2012 - 07:41 PM

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.


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.



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?

#8 Bregma   Crossbones+   -  Reputation: 5499

Like
3Likes
Like

Posted 11 November 2012 - 07:59 PM

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, 11 November 2012 - 07:59 PM.

Stephen M. Webb
Professional Free Software Developer

#9 kd7tck   Members   -  Reputation: 719

Like
6Likes
Like

Posted 11 November 2012 - 07:59 PM

Goto was really meant for use when inlining assembly or linking in outside binaries. I use goto all the time when using assembly, it simplifies loops when otherwise a conditional jump might not be necessary for infinite loops. When doing c++ in a purely OOP world, you should never use goto.

#10 Mussi   Crossbones+   -  Reputation: 2106

Like
7Likes
Like

Posted 11 November 2012 - 08:29 PM

You don't need an object to get rid of your goto. Take a step back and look at what you're trying to accomplish. You basically want to loop when some condition is met, this is exactly what while/do while/ for loops are meant to do. You can make a function out of the battlemenu section, return true when you have to execute it again or false otherwise. Then you simply call while( battlemenu() ) {}.

#11 petrusd987   Members   -  Reputation: 108

Like
0Likes
Like

Posted 11 November 2012 - 10:50 PM

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, 11 November 2012 - 10:51 PM.


#12 rnlf   Members   -  Reputation: 1185

Like
3Likes
Like

Posted 12 November 2012 - 12:45 AM

goto still has its place in C (take a look at the Linux kernel for lots of examples of non-destructive goto use), but for me there has never been any sensible reason to use it in C++.

my blog (German)


#13 Sparkon   Members   -  Reputation: 395

Like
1Likes
Like

Posted 12 November 2012 - 01:29 AM

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 http://www.u.arizona.edu/~rubinson/copyright_violations/Go_To_Considered_Harmful.html that was written by dijkstra about the use of GOTO statement. It's a good read!

#14 apatriarca   Crossbones+   -  Reputation: 1769

Like
0Likes
Like

Posted 12 November 2012 - 02:55 AM

This is not really related to your question, but I think you may be interested to recieve other feedbacks on your code.

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

#15 Bacterius   Crossbones+   -  Reputation: 9304

Like
3Likes
Like

Posted 12 November 2012 - 03:25 AM

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.

The slowsort algorithm is a perfect illustration of the multiply and surrender paradigm, which is perhaps the single most important paradigm in the development of reluctant algorithms. The basic multiply and surrender strategy consists in replacing the problem at hand by two or more subproblems, each slightly simpler than the original, and continue multiplying subproblems and subsubproblems recursively in this fashion as long as possible. At some point the subproblems will all become so simple that their solution can no longer be postponed, and we will have to surrender. Experience shows that, in most cases, by the time this point is reached the total work will be substantially higher than what could have been wasted by a more direct approach.

 

- Pessimal Algorithms and Simplexity Analysis


#16 rip-off   Moderators   -  Reputation: 8764

Like
6Likes
Like

Posted 12 November 2012 - 04:18 AM

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:
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;
	    return;
    }
   
    bool action = false;
    while(!action) {
	    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);
			    action = true;
			    break;
				
		    case 2:
			    cout << "\n----------------- Battle Results ------------------" << endl;
			    if(C.ammo == 0) {
				    cout << "You're out of ammo! \n" << endl;
			    } else {
				    C.gunAttack(M);
				    action = true;
			    }
			    break;
				
		    case 3:
			    cout << "\n----------------- Battle Results ------------------" << endl;
			    if(C.potions == 0) {
				    cout << "You're out of potions! \n" << endl;
			    } else {
				    C.useHP();
				    action = true;
			    }
			    break;
	    }
    }
}
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:
#include <string>
#include <vector>
struct CombatAction {
    typedef void (*ActionFunctionPtr)(Character &character, Monster &monster);
    string name;
    ActionFunctionPtr action;
   
    CombatAction(const string &name, ActionFunctionPtr action)
    :
	    name(name),
	    action(action)
    {
    }
};
void punch(Character &character, Monster &monster) {
    character.meleeAttack(monster);
}
void shoot(Character &character, Monster &monster) {
    character.gunAttack(monster);
}
void heal(Character &character, Monster & /* unusued */) {
    character.useHP();
}
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;
	    return;
    }
   
    vector<CombatAction> actions;
    actions.push_back(CombatAction("Melee Attack", &punch));
    if(c.ammo > 0) {
	    actions.push_back(CombatAction("Gun Attack", &shoot));
    }
    if(c.potions > 0) {
	    actions.push_back(CombatAction("Health Potion", &heal);
    }
   
    bool action = false;
    while(!action) {
	    cout << "----------------- Battle Options ------------------" << endl;
	    C.Display();
	    cout << "What do you want to do? \n";
	    cout << "Type the number of the action and press enter. \n";
	    for(size_t i = 0 ; i < actions.size() ; ++i) {
		    cout << "[" << (i + 1) << "] " << actions[i].name << '\n';
	    }
	
	    size_t choice;
	    cin >> choice;
	    if(choice > 0 && choice <= actions.size()) {
		    cout << "\n----------------- Battle Results ------------------" << endl;
		    actions[choice - 1].action(C, M);
		    action = true;
	    } else {
		    cout << "Invalid option!" << endl;
	    }
    }
}
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.

Note: I haven't compiled or tested any of the code in this post, so caveat emptor.

#17 Olaf Van Schlacht   Members   -  Reputation: 767

Like
0Likes
Like

Posted 12 November 2012 - 05:36 AM

My Teacher always told me that GOTO is forbidden.

printf("Hello Signature");


#18 Lauris Kaplinski   Members   -  Reputation: 841

Like
4Likes
Like

Posted 12 November 2012 - 05:46 AM

If you are posting in beginners forum then you shouldn't use goto in your code Posted Image
Once you reach advanced level... well, then you know yourself.
Lauris Kaplinski

First technology demo of my game Shinya is out: http://lauris.kaplinski.com/shinya
Khayyam 3D - a freeware poser and scene builder application: http://khayyam.kaplinski.com/

#19 Felix Ungman   Members   -  Reputation: 1066

Like
0Likes
Like

Posted 12 November 2012 - 06:24 AM

If you are posting in beginners forum then you shouldn't use goto in your code Posted Image
Once you reach advanced level... well, then you know yourself.


...then you'll rather use comefrom (http://en.wikipedia.org/wiki/Comefrom)

openwar  - the real-time tactical war-game platform


#20 Karsten_   Members   -  Reputation: 1655

Like
5Likes
Like

Posted 12 November 2012 - 07:52 AM

When writing C, I use goto quite a lot for error handling and cleanup before returning an error code (rather than writing repetitive code after each failure check).

For those who are convinced that goto is bad in every single situation, have a look at the OpenBSD source code (which is renowned for good code quality) and you will see that goto is used very often.

For C++ however, I find that with RAII (and smart pointers), if you just throw an exception (or even return an error code) then all memory is cleaned up anyway.

Mutiny - Open-source C++ Unity re-implementation.
Defile of Eden 2 - FreeBSD and OpenBSD binaries of our latest game.





Old topic!
Guest, the last post of this topic is over 60 days old and at this point you may not reply in this topic. If you wish to continue this conversation start a new topic.



PARTNERS