0

I recently started learning c++, and I am just testing what I know by making a terrible little game.

I want to jump back in my code, so I learnt about a goto statment. Here is my code(not all of it, just the goto bit)

moving: if(moveChoice == "Forward"){ cout << "You moved Forward" << endl; moveChoice = ""; if(firstTargetRand == 2){ cout << "You encountered a tree!" << endl; }if(firstTargetRand != 2){ cout << "goto init" << endl; goto moving; } } 

Now "goto moving" is getting called ( checked with cout goto init ) but this isn't working. I know this is prob a really stupid mistake, but I can't see anything wrong with it

10
  • 1
    With the amount of information presented, all I can tell you is you're wrong, goto is working fine. Couldn't tell you where you're wrong though without knowing what you're doing. Commented Jul 14, 2014 at 19:18
  • 4
    My top guess is that your moveChoice is of type char*. Change it to std::string to fix the first problem. The second problem would be to un-learn the goto ;-) Commented Jul 14, 2014 at 19:19
  • 8
    better yet would be to learn how to write code without goto's. they have very few valid usage cases, and this isn't one of them. Commented Jul 14, 2014 at 19:19
  • 3
    @user3532547, goto is just about the easiest way to get spaghetti code if not used correctly. This code is a prime candidate for a loop. Commented Jul 14, 2014 at 19:28
  • 3
    @user3532547 If you would like to know what's wrong with goto, this article is a good place to start. Commented Jul 14, 2014 at 19:28

1 Answer 1

4

Well, first of all, I feel obligated to mention that goto is frowned upon for pretty much any use, and like the comments say, this is prime loop material.

Your problem is that you are checking if moveChoice == "Forward", then setting moveChoice to "", then going back, and then moveChoice == "Forward" always returns 0.

If you really want the goto, try this:

if(moveChoice == "Forward"){ moving: cout << "You moved Forward" << endl; moveChoice = ""; if(firstTargetRand == 2){ cout << "You encountered a tree!" << endl; }else{ cout << "goto init" << endl; goto moving; } } 

If you aren't terribly partial to the goto, try this:

while(moveChoice=="Forward"){ cout << "You moved Forward" << end1; if(firstTargetRand == 2){ cout << "You encountered a tree!" << end1; moveChoice = ""; }else{ cout << "goto init" << end1; } } 
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for the answer! I just fixed this another way(still using while though). However, this does look a lot better ^.^ thanks!
You did not remove goto moving; from the else{} in your while() example.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.