What you are trying to do - jump between functions - is not valid for a whole host of reasons, not least being an area of โโobjects and a lifetime, consider:
void foo() { if(feelLikeIt) goto foobar; } void bar() { std::string message = "Hello"; foobar: cout << message << endl; }
Jumping to foobar from foo is illegal because the "message" will not exist.
Thus, the language simply does not allow you to do this.
Also, the way you are trying to use "goto" will not allow you to reuse the "fruit ()" function, because it always decides what to do with the choice and not the calling function. What if you want to do this:
cout<<"What do you want to eat? (a/b)"; fruit(); foo: cout<<"You eat an apple."; fooo: cout<<"You eat a banana."; cout<<"What does your friend want to eat? (a/b)"; fruit();
What you STRONGLY want to do is use the "fruit ()" function as a function that returns a value.
enum Fruit { NoSuchFruit, Apple, Banana }; Fruit fruit(const char* request) { char foodstuffs; cout << request << " (a/b)"; cin >> foodstuffs; switch (foodstuffs) { case 'a': return Apple; case 'b': return Banana; default: cout << "Don't recognize that fruit (" << foodstuffs << ")." << endl; return NoSuchFruit; } } const char* fruitNames[] = { "nothing", "an apple" ,"a banana" }; int main() { Fruit eaten = fruit("What do you want to eat?"); cout << "You ate " << fruitNames[eaten] << "." << endl; eaten = fruit("What does your friend want to eat?"); cout << "Your friend ate " << fruitNames[eaten] << "." << endl; }
source share