• Announcements

    • khawk

      Download the Game Design and Indie Game Marketing Freebook   07/19/17

      GameDev.net and CRC Press have teamed up to bring a free ebook of content curated from top titles published by CRC Press. The freebook, Practices of Game Design & Indie Game Marketing, includes chapters from The Art of Game Design: A Book of Lenses, A Practical Guide to Indie Game Marketing, and An Architectural Approach to Level Design. The GameDev.net FreeBook is relevant to game designers, developers, and those interested in learning more about the challenges in game development. We know game development can be a tough discipline and business, so we picked several chapters from CRC Press titles that we thought would be of interest to you, the GameDev.net audience, in your journey to design, develop, and market your next game. The free ebook is available through CRC Press by clicking here. The Curated Books The Art of Game Design: A Book of Lenses, Second Edition, by Jesse Schell Presents 100+ sets of questions, or different lenses, for viewing a game’s design, encompassing diverse fields such as psychology, architecture, music, film, software engineering, theme park design, mathematics, anthropology, and more. Written by one of the world's top game designers, this book describes the deepest and most fundamental principles of game design, demonstrating how tactics used in board, card, and athletic games also work in video games. It provides practical instruction on creating world-class games that will be played again and again. View it here. A Practical Guide to Indie Game Marketing, by Joel Dreskin Marketing is an essential but too frequently overlooked or minimized component of the release plan for indie games. A Practical Guide to Indie Game Marketing provides you with the tools needed to build visibility and sell your indie games. With special focus on those developers with small budgets and limited staff and resources, this book is packed with tangible recommendations and techniques that you can put to use immediately. As a seasoned professional of the indie game arena, author Joel Dreskin gives you insight into practical, real-world experiences of marketing numerous successful games and also provides stories of the failures. View it here. An Architectural Approach to Level Design This is one of the first books to integrate architectural and spatial design theory with the field of level design. The book presents architectural techniques and theories for level designers to use in their own work. It connects architecture and level design in different ways that address the practical elements of how designers construct space and the experiential elements of how and why humans interact with this space. Throughout the text, readers learn skills for spatial layout, evoking emotion through gamespaces, and creating better levels through architectural theory. View it here. Learn more and download the ebook by clicking here. Did you know? GameDev.net and CRC Press also recently teamed up to bring GDNet+ Members up to a 20% discount on all CRC Press books. Learn more about this and other benefits here.
Sign in to follow this  
Followers 0
armitroner

C++ - Is Goto a Good Practice?

46 posts in this topic

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!"
1

Share this post


Link to post
Share on other sites
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]
0

Share this post


Link to post
Share on other sites
[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?
0

Share this post


Link to post
Share on other sites
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
0

Share this post


Link to post
Share on other sites
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!
1

Share this post


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

Share this post


Link to post
Share on other sites
[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])
0

Share this post


Link to post
Share on other sites
[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]
0

Share this post


Link to post
Share on other sites
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
2

Share this post


Link to post
Share on other sites
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]
0

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  
Followers 0