GOTO Alternative

  • (5 Pages)
  • +
  • 1
  • 2
  • 3
  • Last »

74 Replies - 3667 Views - Last Post: 26 May 2012 - 03:26 AM Rate Topic: -----

#1 Morrowind_Fan  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 18
  • Joined: 01-May 12

GOTO Alternative

Posted 23 May 2012 - 02:29 PM

I'm looking for an alternative for the many GOTO statements in my code. Being a c++ beginner, I have little knowledge of such things. Can you please point me in the right direction or give me an example?

// Operation Blitzkrieg_satellite.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include <iostream>
#include <cctype>
#include <sstream>
#include <string>
#include <cstdlib>

//namespace
using namespace std;

// variable declarations:
char c1;
char c2;
char c3;
char c4;
bool satfin;

//noticed:
char cn1;
char cn2;

//unoticed:
char cun1;
char cun2;

//main program
int _tmain(int argc, _TCHAR* argv[])
{
	cout << "Your boat lands. As you head up the beach you notice that there is a lone guard on patrol. How do you want to take him out? [input the number corresponding to your answer.]" <<endl;
	cout << " " << endl;
	cout << "1. Sneak up behind him and knife him" << endl;
	cout << "2. Use your G36C suppressed to fire upon him." << endl;
	cout << "3. Use your M98B to take him out from afar." << endl;
	cin >> c1 ;
	if (c1=='1')
        {
            cout << "As you attempt to sneak up behind him to slit his throat, he hears the crunch of your combat boots on the sand. He turns around and shoots you.";
            goto die;
        }
    else if(c1=='2')
        {
            cout << "As you open fire using your suppressed G36C, the guard manages to radio in for help before he dies." << endl;
            cout << "" << endl;
            system("pause");
            system("cls");
			cout << "As you proceed, you are acutely aware of the fact that you are now noticed, and, therefore, you must be prepared for battle ahead." << endl;
			cout << "" << endl;
			system("pause");
			system("cls");
			cout << "Continuing through the bush, you see a large enemy patrol. What would you like to do?" << endl;
			cout << "1. Try to sneak past them." << endl;
			cout << "2. Try to take on the patrol." << endl;
			cout << "3. Try to hide and wait them out." << endl; 
			goto sn1.0;
		}
	else if (c1=='3')
        {
            cout << "Scoping in, you center on the back of his head. In between your heartbeats, you pull the trigger. You grin in satisfaction as his the front of his head explodes outward in a gory mess." << endl;
            cout << "" << endl;
            system("pause");
            system("cls");
			goto sun1.0;
        }

			
			

sn1.0:
		cin >> cn1;
		if (cn1=='1')
		{
			system("cls");
			cout << "You attempt to sneak past; however, one guard heres you and comes searching for you" << endl;
			cout << "What would you like to do?" << endl;
			cout << "1. Try to sneak past the guard" << endl;
			cout << "2. Try to take out the guard" << endl;
			cin >> cn2;
			if (cn2=='1')
				{
					cout << "You manage to sneak behind him, but he hears you step on a twig. He turns around and opens fire on you. Feeling the bullets enter your body, you fade from life" << endl;
					goto die;
				}
				else if (cn2=='2')
				{
					cout << "You shoot him from the cover of the surrounding folliage and he drops like a rock, no one notices that he is dead and you move on unseen" << endl;
					goto sn1.1;
				}
				else if (cn1=='2')
				{
					cout << "As you open fire, your bullets enter two of the guards' chest and kills them. The rest of them open fire and kill you." << endl;
					goto die;
				}
				else if (cn1=='3')
				{
					cout << "Taking cover, the guards walk past you. Unnoticed, you continue onwards" << endl;
					goto sn1.1;
				}
		}
		else if (cn1=='2')

sun1.0:
		cout << "You continue through the underbush towards the objective." << endl;
		system("pause");
		cout << "As you head onward, you come across a larger, better equipped patrol. You have two options: [please input the number corresponding to your choice.]" << endl;
		cout << "1. You can stay hidden, and wait for the patrol to move onward" << endl;
		cout << "2. You can attack the patrol using your submachine gun" << endl;
		cin >> cun1 ;
		if (cun1=='1')
		{
			cout << "The patrol moves on; however, two guards are commanded to stay put. One of the guards is talking into his radio." << endl;
			goto sun1.1;
		}
		else if (cun1=='2')
		{
			cout << "As you open fire, you manage to kill one of the guards; however, your gun jams, and the rest of the 6 man squad open fire. You feel the bullets rip holes in your body" << endl;
			goto die;
		}
sun1.1:
		cout << "Seeing the two guards remaining, you have two options on how to proceed [please input the number corresponding to your choice.]:" << endl;
		cout << "1. You can take out two guards with your submachine gun." << endl;
		cout << "2. You can try to sneak past the two guards to continue onto your objective." << endl;
		cin >> cun2
		if (cun2=='1')
		{
			cout << "You manage to take out both the guards with your submachine gun; however, the guard on the radio lets out a scream which is heard by the man on the other end of the radio." << endl;
			goto sn1.0;
		}
		else if (cun2=='2')
		{
			cout << "You manage to sneak past the two guards, and you move on towards the satellite uplink." << endl;
			goto sun2.0;
		}

sun2.0:
		cout << "C.A.M. : Now you need to upload the virus we provided you on the flashdrive onto the satellite via the uplink" << endl;
		satfin == true;
		goto sf;

sf:
		if ((intfin == false) && (airfin == false))
		{
			cout << "You have successfully uploaded the virus to the satellite. Now you have to options: You can move onto the airfield or to retrieve the intel" << endl;
			cout << "Move on to steal the intel" << endl;
			cout << "Move on to destroy the airfield" << endl;
			cin c2;
			f (c4=='1')
			{
				goto intstart;
			}
			else if (c4 == '2')
			{
				goto airstart;
			}

		}
		else if (infin == false) && (airfin == true)
		{
			cout << "You have one more objective: to steal the intelligence we need." << endl;
			goto intstart;
		}
		else if (infin == true) && (airfin == false)
		{
			cout << "You have successfully uploaded the virus to the sattelite and stolen the intel document. You can either attempt to make it to the landing zone or you can try to destroy the airfeild.[input the number corresponding to your choice]" << endl;
			cout << "Try to go to the airfield" << endl;
			cout << "Try to go to the landing zone" << endl;
			cin >> c4;
			if (c4=='1')
			{
				goto airstart;
			}
			else if (c4 == '2')
			{
				cout << "The enemies notice that the satellite is not working properly and that intel is stolen. They sound the alarms and scramble jets and helicopters to search for you. A helicopter spots you as you are running for the helicopter and opens fire. Feeling the bullets enter your body, you fade from life." endl;
				goto die;
			}

die:
	cout << "You have died; mission failed." << endl;
	goto start;

}



Is This A Good Question/Topic? 1
  • +

Replies To: GOTO Alternative

#2 mccabec123  Icon User is offline

  • D.I.C Head

Reputation: 18
  • View blog
  • Posts: 233
  • Joined: 03-March 11

Re: GOTO Alternative

Posted 23 May 2012 - 02:34 PM

Don't use goto's ever, it's incredibly bad practice, either find another way to do it or stop programming altogether. For each goto you have to perform two more tests on your system. If you value yourself as a programmer you should learn never to use them, ever.

Why aren't you using functions for this anyway? I do not understand.

This post has been edited by mccabec123: 24 May 2012 - 11:49 AM

Was This Post Helpful? 1
  • +
  • -

#3 mojo666  Icon User is offline

  • D.I.C Addict
  • member icon

Reputation: 356
  • View blog
  • Posts: 783
  • Joined: 27-June 09

Re: GOTO Alternative

Posted 23 May 2012 - 03:31 PM

There are a few ways to go about this. mccabec already suggested functions, however if you do not know what functions are yet, you could use a loop, a string containing the goto name and series of ifs/elseifs to execute code based on that string. Every block of code beloning to a label will be in an elseif that tests if the string is equal to the label. Instead of calling goto, just update the string to the new label. It would look somewhat like the following.

int main()
{
     string step="start";
     while(step!="End";
     {
          if(step=="start")
          {
               cout>>"Enter 1 or two";
               cin<<step;
          }
          else if(step=="1")
          {
               cout<<"What a boring choice.  I don't want to play anymore."
               step="EndGame";
          }
          else if(step=="2")
          {
               cout<<"I said two, not \"2\"!  I don't want to play anymore."
               step="EndGame";
          }
          else if(step=="two")
          {
               cout<<"Good choice.  You win!"
               step="EndGame";
          }
          else if(step=="EndGame")
          {
               cout<<"The game is over."
               cin<<step;
               step="End";
          }
     }
     return 0
}


Was This Post Helpful? 1
  • +
  • -

#4 ishkabible  Icon User is offline

  • spelling expret
  • member icon




Reputation: 1623
  • View blog
  • Posts: 5,709
  • Joined: 03-August 09

Re: GOTO Alternative

Posted 23 May 2012 - 03:55 PM

better yet, rather than all those strings, use a switch case and some enums. most compilers recognize the state machine idiom and will produce code that immediately jumps to the correct position if it can be predicted(in this case it can) and/or uses a jump table.

there are a few case where goto is ok in C and for highly optimized code it can sometimes be useful(like, hardcore standard library stuff where saving 2 cycles can mean saving money off of server time) but I can assure you, this is not any of those cases.

just forget you ever learned about goto and labels for now.

This post has been edited by ishkabible: 23 May 2012 - 04:01 PM

Was This Post Helpful? 1
  • +
  • -

#5 mccabec123  Icon User is offline

  • D.I.C Head

Reputation: 18
  • View blog
  • Posts: 233
  • Joined: 03-March 11

Re: GOTO Alternative

Posted 23 May 2012 - 03:59 PM

View Postmojo666, on 23 May 2012 - 03:31 PM, said:

There are a few ways to go about this. mccabec already suggested functions, however if you do not know what functions are yet, you could use a loop, a string containing the goto name and series of ifs/elseifs to execute code based on that string. Every block of code beloning to a label will be in an elseif that tests if the string is equal to the label. Instead of calling goto, just update the string to the new label. It would look somewhat like the following.

int main()
{
     string step="start";
     while(step!="End";
     {
          if(step=="start")
          {
               cout>>"Enter 1 or two";
               cin<<step;
          }
          else if(step=="1")
          {
               cout<<"What a boring choice.  I don't want to play anymore."
               step="EndGame";
          }
          else if(step=="2")
          {
               cout<<"I said two, not \"2\"!  I don't want to play anymore."
               step="EndGame";
          }
          else if(step=="two")
          {
               cout<<"Good choice.  You win!"
               step="EndGame";
          }
          else if(step=="EndGame")
          {
               cout<<"The game is over."
               cin<<step;
               step="End";
          }
     }
     return 0
}



There is no alternative to using functions for this, learn how to code properly from the start, do not use goto's it's sloppy and lazy, and also incredibly bad because it upsets the natural structure of a program, it tells the system to think a way that it is not meant to think, which is line by line. Here's a document produced by a university lecturer stating why goto's are horrific and should not exist within High Level Languages: http://www.u.arizona...ed_Harmful.html

Also you would use a switch instead of if statements, you could use if statements, but it requires far less coding using switch statements for this type of problem. Here is some help with switch statements: http://www.cplusplus.../general/29910/
Was This Post Helpful? 0
  • +
  • -

#6 turboscrew  Icon User is offline

  • D.I.C Addict

Reputation: 100
  • View blog
  • Posts: 644
  • Joined: 03-April 12

Re: GOTO Alternative

Posted 23 May 2012 - 08:26 PM

Try to use intercal instead of C and use "come from". :lol:

No, really: restructure your code.
You need to change your thinking from linear language (like basic or fortran) to (block)structured language.

State machines are always a bit more complicated in block structured languages than linear languages (maybe excluding occam).

This:

Quote

Don't use goto's ever, it's incrdibly bad practice, either find another way to do it or stop programming altogether.
is bull...

Dijkstra wrote that article when the structured languages were hot, but it's not the whole truth. For example, gotos are used a lot in error handling. A little bit like C++ exceptions.

When people started programming with basic - back in 80's, these kind of beginner problems with pascal were very common.
Was This Post Helpful? 3
  • +
  • -

#7 David W  Icon User is offline

  • DIC supporter
  • member icon

Reputation: 281
  • View blog
  • Posts: 1,788
  • Joined: 20-September 08

Re: GOTO Alternative

Posted 23 May 2012 - 09:16 PM

If you ever program in assembly ... you will note that all those nice high level structures are built from a careful use of varations of 'goto' ... (jump to ...)

See some examples here:

http://webster.cs.uc.../WhatIsHLA.html

http://webster.cs.uc...LDoc/while.html

This post has been edited by David W: 23 May 2012 - 09:19 PM

Was This Post Helpful? 1
  • +
  • -

#8 baavgai  Icon User is online

  • Dreaming Coder
  • member icon

Reputation: 5907
  • View blog
  • Posts: 12,813
  • Joined: 16-October 07

Re: GOTO Alternative

Posted 24 May 2012 - 07:37 AM

It's not just the gotos, though that's dire. It's globals, variables not defined, extra variables you don't need, everything in main... so many things, really.

It would help if this even compiled. Let's get it that far.
#include <iostream>
#include <cctype>
#include <sstream>
#include <string>
#include <cstdlib>

//namespace
using namespace std;

// global declaration BAD!
// variable declarations:
char c1;
// char c2; never used
// char c3; never used
char c4;
bool satfin;

//noticed:
char cn1;
char cn2;

//unoticed:
char cun1;
char cun2;


// everything in one function?!?
int main() {
	bool infin, intfin, airfin; // this was never declared
	cout << "Your boat lands. As you head up the beach you notice that there is a lone guard on patrol. How do you want to take him out? [input the number corresponding to your answer.]" << endl;
	cout << " " << endl;
	cout << "1. Sneak up behind him and knife him" << endl;
	cout << "2. Use your G36C suppressed to fire upon him." << endl;
	cout << "3. Use your M98B to take him out from afar." << endl;
	cin >> c1;
	if (c1 == '1') {
		cout << "As you attempt to sneak up behind him to slit his throat, he hears the crunch of your combat boots on the sand. He turns around and shoots you.";
		goto die;
	} else if (c1 == '2') {
		cout << "As you open fire using your suppressed G36C, the guard manages to radio in for help before he dies." << endl;
		cout << "" << endl;
		system("pause");
		system("cls");
		cout << "As you proceed, you are acutely aware of the fact that you are now noticed, and, therefore, you must be prepared for battle ahead." << endl;
		cout << "" << endl;
		system("pause");
		system("cls");
		cout << "Continuing through the bush, you see a large enemy patrol. What would you like to do?" << endl;
		cout << "1. Try to sneak past them." << endl;
		cout << "2. Try to take on the patrol." << endl;
		cout << "3. Try to hide and wait them out." << endl;
		goto sn1_0;
	} else if (c1 == '3') {
		cout << "Scoping in, you center on the back of his head. In between your heartbeats, you pull the trigger. You grin in satisfaction as his the front of his head explodes outward in a gory mess." << endl;
		cout << "" << endl;
		system("pause");
		system("cls");
		goto sun1_0;
	}




sn1_0:
	cin >> cn1;
	if (cn1 == '1') {
		system("cls");
		cout << "You attempt to sneak past; however, one guard heres you and comes searching for you" << endl;
		cout << "What would you like to do?" << endl;
		cout << "1. Try to sneak past the guard" << endl;
		cout << "2. Try to take out the guard" << endl;
		cin >> cn2;
		if (cn2 == '1') {
			cout << "You manage to sneak behind him, but he hears you step on a twig. He turns around and opens fire on you. Feeling the bullets enter your body, you fade from life" << endl;
			goto die;
		} else if (cn2 == '2') {
			cout << "You shoot him from the cover of the surrounding folliage and he drops like a rock, no one notices that he is dead and you move on unseen" << endl;
			goto sn1_1;
		// you can never get here!!!  cn1=='1'
		} else if (cn1 == '2') {
			cout << "As you open fire, your bullets enter two of the guards' chest and kills them. The rest of them open fire and kill you." << endl;
			goto die;
		} else if (cn1 == '3') {
			cout << "Taking cover, the guards walk past you. Unnoticed, you continue onwards" << endl;
			goto sn1_1;
		}
	} else if (cn1 == '2')

sun1_0:
	cout << "You continue through the underbush towards the objective." << endl;
	system("pause");
	cout << "As you head onward, you come across a larger, better equipped patrol. You have two options: [please input the number corresponding to your choice.]" << endl;
	cout << "1. You can stay hidden, and wait for the patrol to move onward" << endl;
	cout << "2. You can attack the patrol using your submachine gun" << endl;
	cin >> cun1;
	if (cun1 == '1') {
		cout << "The patrol moves on; however, two guards are commanded to stay put. One of the guards is talking into his radio." << endl;
		goto sun1_1;
	} else if (cun1 == '2') {
		cout << "As you open fire, you manage to kill one of the guards; however, your gun jams, and the rest of the 6 man squad open fire. You feel the bullets rip holes in your body" << endl;
		goto die;
	}
sun1_1:
	cout << "Seeing the two guards remaining, you have two options on how to proceed [please input the number corresponding to your choice.]:" << endl;
	cout << "1. You can take out two guards with your submachine gun." << endl;
	cout << "2. You can try to sneak past the two guards to continue onto your objective." << endl;
	cin >> cun2; // missing ;
	if (cun2 == '1') {
		cout << "You manage to take out both the guards with your submachine gun; however, the guard on the radio lets out a scream which is heard by the man on the other end of the radio." << endl;
		goto sn1_0;
	} else if (cun2 == '2') {
		cout << "You manage to sneak past the two guards, and you move on towards the satellite uplink." << endl;
		goto sun2_0;
	}

sun2_0:
	cout << "C.A.M. : Now you need to upload the virus we provided you on the flashdrive onto the satellite via the uplink" << endl;
	// wrong
	//satfin == true;
	satfin = true;
	// why, if it's right below?
	// goto sf;

sf:
	if (!intfin && airfin) {
		cout << "You have successfully uploaded the virus to the satellite. Now you have to options: You can move onto the airfield or to retrieve the intel" << endl;
		cout << "Move on to steal the intel" << endl;
		cout << "Move on to destroy the airfield" << endl;
		// huh?
		// cin c2;
		// ???
		// f(c4 == '1') {
		if(c4 == '1') {
			goto intstart;
		} else if (c4 == '2') {
			goto airstart;
		}

	// ??
	// } else if (infin == false) && (airfin == true) {
	} else if (!infin && airfin) {
		cout << "You have one more objective: to steal the intelligence we need." << endl;
		goto intstart;
	// ??
	// } else if (infin == true) && (airfin == false) {
	} else if (infin && !airfin) {
		cout << "You have successfully uploaded the virus to the sattelite and stolen the intel document. You can either attempt to make it to the landing zone or you can try to destroy the airfeild.[input the number corresponding to your choice]" << endl;
		cout << "Try to go to the airfield" << endl;
		cout << "Try to go to the landing zone" << endl;
		cin >> c4;
		if (c4 == '1') {
			goto airstart;
		} else if (c4 == '2') {
			cout << "The enemies notice that the satellite is not working properly and that intel is stolen. They sound the alarms and scramble jets and helicopters to search for you. A helicopter spots you as you are running for the helicopter and opens fire. Feeling the bullets enter your body, you fade from life." << endl; // missing <<
			goto die;
		}
	} // this was missing!!


	// just to let you know
	cout << "oops, no one should get here" << endl;

die:
	cout << "You have died; mission failed." << endl;
	goto start;

// where all your undefined labels go to die
sn1_1:
intstart:
airstart:
start:
	cout << "undefined label" << endl;
	return 1;

}




This is more a puzzle than anything else. Since you've obviously never run it, you can't spot that the puzzle is broken. If it worked, then it would be more fun to get it working properly.

Here's one attempt at cleanup:
#include <iostream>

struct State {
	enum Location { 
		LOC_DIE, LOC_DONE,
		LOC_START, LOC_SN, LOC_SUN, LOC_SUN2, LOC_SF,
		LOC_INT_START, LOC_AIR_START
	};
	Location loc;
	int locStep;
	bool infin, airfin, satfin;
};


bool processStart(State &);
bool processSn(State &);
bool processSun(State &);
bool processSun2(State &);
bool processSf(State &);
bool processCrap(State &);
bool processDie(State &);

int main() {
	State state;
	state.loc = State::LOC_START;
	state.satfin = state.infin = state.airfin = false;
	while(state.loc != State::LOC_DONE) {
		processStart(state)
		|| processSn(state)
		|| processSun(state)
		|| processSun2(state)
		|| processSf(state)
		|| processDie(state)
		|| processCrap(state);
	}
	return 0;
}

using namespace std;

int getChoice() { 
	int n; 
	while (!(cin >> n)) { cin.clear(); cin.ignore(); }
	return n;
}

int getChoice(int max, int min=1) {
	int n = 0;
	while(n==0) {
		n = getChoice();
		if (n>=min && n<=max) { break; }
		cout << "Invalid choice." <<endl;
		n = 0;
	}
	return n;
};

void cls() { 
	// bad idea anyway
	// system("cls");
}

void pauseInput() {
	// system("pause");
}

void pauseCls() {
	cout << endl;
	pauseInput();
	cls();
}

bool processStart(State &s) {
	if (s.loc!=State::LOC_START) { return false; }
	cout << "Your boat lands. As you head up the beach you notice that there is a lone guard on patrol. How do you want to take him out? [input the number corresponding to your answer.]" << endl;
	cout << " " << endl;
	cout << "1. Sneak up behind him and knife him" << endl;
	cout << "2. Use your G36C suppressed to fire upon him." << endl;
	cout << "3. Use your M98B to take him out from afar." << endl;
	int choice = getChoice(3);
	if (choice == 1) {
		cout << "As you attempt to sneak up behind him to slit his throat, he hears the crunch of your combat boots on the sand. He turns around and shoots you.";
		s.loc = State::LOC_DIE;
		
	} else if (choice == 2) {
		s.loc = State::LOC_SN; s.locStep = -1;
		
	} else if (choice == 3) {
		cout << "Scoping in, you center on the back of his head. In between your heartbeats, you pull the trigger. You grin in satisfaction as his the front of his head explodes outward in a gory mess." << endl;
		pauseCls();
		s.loc = State::LOC_SUN; s.locStep = 0;
	}
	return true;
}


bool processSn(State &s) {
	if (s.loc!=State::LOC_SN) { return false; }
	if (s.locStep==-1) {
		pauseCls();
		cout << "Continuing through the bush, you see a large enemy patrol. What would you like to do?" << endl;
		cout << "1. Try to sneak past them." << endl;
		cout << "2. Try to take on the patrol." << endl;
		cout << "3. Try to hide and wait them out." << endl;
		s.locStep=0;
	} else if (s.locStep==0) {
		int choice = getChoice(3); // your logic, not mine
		if (choice==1) {
			cls();
			cout << "You attempt to sneak past; however, one guard heres you and comes searching for you" << endl;
			cout << "What would you like to do?" << endl;
			cout << "1. Try to sneak past the guard" << endl;
			cout << "2. Try to take out the guard" << endl;
			int choice2 = getChoice(2);
			if (choice2 == 1) {
				cout << "You manage to sneak behind him, but he hears you step on a twig. He turns around and opens fire on you. Feeling the bullets enter your body, you fade from life" << endl;
				s.loc = State::LOC_DIE;
			} else if (choice == 2) {
				cout << "You shoot him from the cover of the surrounding folliage and he drops like a rock, no one notices that he is dead and you move on unseen" << endl;
				cout << "Alas, no sn1_1 defined, you die." << endl;
				s.loc = State::LOC_DIE;
			}
		} else if (choice==2) {
			s.loc = State::LOC_SUN; s.locStep = 0;
		} else if (choice==3) {
			cout << "No choice 3 defined, you die" << endl;
			s.loc = State::LOC_DIE;
		} else  {
			// shouldn't get here
			return false;
		}
	} else {
		// shouldn't get here
		return false;
	}
	return true;
}


bool processSun(State &s) {
	if (s.loc!=State::LOC_SUN) { return false; }
	if (s.locStep==0) {
		cout << "You continue through the underbush towards the objective." << endl;
		pauseInput();
		cout << "As you head onward, you come across a larger, better equipped patrol. You have two options: [please input the number corresponding to your choice.]" << endl;
		cout << "1. You can stay hidden, and wait for the patrol to move onward" << endl;
		cout << "2. You can attack the patrol using your submachine gun" << endl;
		int choice = getChoice(2);
		if (choice == 1) {
			cout << "The patrol moves on; however, two guards are commanded to stay put. One of the guards is talking into his radio." << endl;
			s.locStep=1;
		} else if (choice == 2) {
			cout << "As you open fire, you manage to kill one of the guards; however, your gun jams, and the rest of the 6 man squad open fire. You feel the bullets rip holes in your body" << endl;
			s.loc = State::LOC_DIE;
		}
	} else if (s.locStep==1) {
		cout << "Seeing the two guards remaining, you have two options on how to proceed [please input the number corresponding to your choice.]:" << endl;
		cout << "1. You can take out two guards with your submachine gun." << endl;
		cout << "2. You can try to sneak past the two guards to continue onto your objective." << endl;
		int choice = getChoice(2);
		if (choice == 1) {
			cout << "You manage to take out both the guards with your submachine gun; however, the guard on the radio lets out a scream which is heard by the man on the other end of the radio." << endl;
			s.loc = State::LOC_SN; s.locStep = 0;
		} else if (choice == 2) {
			cout << "You manage to sneak past the two guards, and you move on towards the satellite uplink." << endl;
			s.loc = State::LOC_SUN2;
		}
	}
	return true;
}

bool processSun2(State &s) {
	if (s.loc!=State::LOC_SUN2) { return false; }
	cout << "C.A.M. : Now you need to upload the virus we provided you on the flashdrive onto the satellite via the uplink" << endl;
	s.satfin = true;
	s.loc = State::LOC_SF;
	return true;
}


bool processSf(State &s) {
	if (s.loc!=State::LOC_SF) { return false; }
	if (!s.infin && s.airfin) {
		cout << "You have successfully uploaded the virus to the satellite. Now you have to options: You can move onto the airfield or to retrieve the intel" << endl;
		cout << "1. Move on to steal the intel" << endl;
		cout << "2. Move on to destroy the airfield" << endl;
		int choice = getChoice(2);
		if (choice == 1) {
			s.loc = State::LOC_INT_START;
		} else if (choice == 2) {
			s.loc = State::LOC_AIR_START;
		}
	} else if (!s.infin && s.airfin) {
		cout << "You have one more objective: to steal the intelligence we need." << endl;
		s.loc = State::LOC_INT_START;
		
	} else if (s.infin && !s.airfin) {
		cout << "You have successfully uploaded the virus to the sattelite and stolen the intel document. You can either attempt to make it to the landing zone or you can try to destroy the airfeild.[input the number corresponding to your choice]" << endl;
		cout << "1. Try to go to the airfield" << endl;
		cout << "2. Try to go to the landing zone" << endl;
		int choice = getChoice(2);
		if (choice == 1) {
			s.loc = State::LOC_AIR_START;
		} else if (choice == 2) {
			cout << "The enemies notice that the satellite is not working properly and that intel is stolen. They sound the alarms and scramble jets and helicopters to search for you. A helicopter spots you as you are running for the helicopter and opens fire. Feeling the bullets enter your body, you fade from life." << endl;
			s.loc = State::LOC_DIE;
		}
	} else {
		cout << "Not all options addressed, you die" << endl;
		s.loc = State::LOC_DIE;
	}
	return true;
}

bool processCrap(State &s) {
	cout << "Processing for this location not defined, you die" << endl;
	s.loc = State::LOC_DIE;
	return true;
}


bool processDie(State &s) {
	if (s.loc!=State::LOC_DIE) { return false; }
	cout << "You have died; mission failed." << endl;
	s.loc = State::LOC_DONE;
	return true;
}



This is more messy than it need be because it attempts to closely follow the given logic. That logic often fails. Additionally, the names (sn,sun) are fundamentally worthless.

Since the process involves giving a series of choices and then changing to a different place based on choices and state, this would lend itself to an OOP design.
Was This Post Helpful? 2
  • +
  • -

#9 jon.kiparsky  Icon User is offline

  • Pancakes!
  • member icon


Reputation: 7963
  • View blog
  • Posts: 13,581
  • Joined: 19-March 11

Re: GOTO Alternative

Posted 24 May 2012 - 08:39 AM

View Postturboscrew, on 23 May 2012 - 10:26 PM, said:

This:

Quote

Don't use goto's ever, it's incrdibly bad practice, either find another way to do it or stop programming altogether.
is bull...

Dijkstra wrote that article when the structured languages were hot, but it's not the whole truth. For example, gotos are used a lot in error handling. A little bit like C++ exceptions.

When people started programming with basic - back in 80's, these kind of beginner problems with pascal were very common.



Not to get argumentative, but I think that there's no place for goto in higher-level programming. If you're writing exception handling, you're writing low-level code. If you're writing an application, you shouldn't be also writing your error handling at the same time. If you're writing both the application code and the error-handling code, this is a case for a managed schizophrenia: you need to know who you are at this particular moment, and either you're writing low-level code or you're calling that code, but you should never be mixing up those roles. That way madness lies.

Quote

If you ever program in assembly ... you will note that all those nice high level structures are built from a careful use of varations of 'goto' ... (jump to ...)


Could not possibly be more irrelevant. It's true that there are gotos all over the place in the underlying code, but the important word there is "underlying". Ifs, loops, breaks, and returns all generate gotos, but they are not themselves gotos. The difference is that each of these constructs is constrained, which means you know what you need to test for. Specifically, for a given landing point, you can know how you can get to that point.
The exception to that rule is a function, which can be reached from anywhere (you can only know by grepping the name of the function, and not even then if there are function pointers used) but when you write a function, you take that into account - which is where we get a lot of the rules of good programming, ie, avoid globals, avoid side-effects, etc.

So I think Dijkstra was right, and remains right. Goto is not a tool that anyone should use unless they're writing low-level code. A text adventure game is not low-level code.
Was This Post Helpful? 4
  • +
  • -

#10 baavgai  Icon User is online

  • Dreaming Coder
  • member icon

Reputation: 5907
  • View blog
  • Posts: 12,813
  • Joined: 16-October 07

Re: GOTO Alternative

Posted 24 May 2012 - 08:53 AM

Every so often someone gets all bent with the "no goto" mantra. I really don't know why. Any experienced programmer will be familiar with the issues and reasoning. Have I used gotos? Sure, in the dark ages. Have I used them in C, C++, C# ( yeah, C# even has the nasty old things )? No, never. Because, well, why?

There are certain languages that need goto because of their design. In assembly, of course, a JMP is a goto. In BASIC from the line number days. I use goto often in T-SQL; a miserable database semi procedural language where goto is one of the few flow control options.

You see goto in C in old programs ( or programs from old programmers ) to leave with cleanup. It's never required, just easy. Again, goto is NEVER required. I have a standing challenge to anyone to offer code that requires goto...
Was This Post Helpful? 1
  • +
  • -

#11 GWatt  Icon User is offline

  • member icon

Reputation: 278
  • View blog
  • Posts: 3,078
  • Joined: 01-December 05

Re: GOTO Alternative

Posted 24 May 2012 - 09:18 AM

While not required, goto does still have a use in C programming. When dealing with system calls I find it easier to do my exception handling with gotos and labels than creating several functions that (IMO) unnecessarily split up the program logic.

edit:
whoops. Didn't see that jon.kiparsky had already mentioned exception handling.

This post has been edited by GWatt: 24 May 2012 - 09:24 AM

Was This Post Helpful? 0
  • +
  • -

#12 BobRodes  Icon User is offline

  • Your Friendly Local Curmudgeon
  • member icon

Reputation: 574
  • View blog
  • Posts: 2,989
  • Joined: 19-May 09

Re: GOTO Alternative

Posted 24 May 2012 - 09:40 AM

View Postjon.kiparsky, on 24 May 2012 - 10:39 AM, said:

A text adventure game is not low-level code.

What if you write it in assembly? :P
Was This Post Helpful? 0
  • +
  • -

#13 jon.kiparsky  Icon User is offline

  • Pancakes!
  • member icon


Reputation: 7963
  • View blog
  • Posts: 13,581
  • Joined: 19-March 11

Re: GOTO Alternative

Posted 24 May 2012 - 09:47 AM

View PostBobRodes, on 24 May 2012 - 11:40 AM, said:

View Postjon.kiparsky, on 24 May 2012 - 10:39 AM, said:

A text adventure game is not low-level code.

What if you write it in assembly? :P


Don't worry, I won't. I am neither a mad dog nor an Englishman.
Was This Post Helpful? 0
  • +
  • -

#14 David W  Icon User is offline

  • DIC supporter
  • member icon

Reputation: 281
  • View blog
  • Posts: 1,788
  • Joined: 20-September 08

Re: GOTO Alternative

Posted 24 May 2012 - 10:14 AM

View Postjon.kiparsky, on 24 May 2012 - 12:47 PM, said:

View PostBobRodes, on 24 May 2012 - 11:40 AM, said:

View Postjon.kiparsky, on 24 May 2012 - 10:39 AM, said:

A text adventure game is not low-level code.

What if you write it in assembly? :P


Don't worry, I won't. I am neither a mad dog nor an ...


What I was attempting to say was that goto's have their proper place, and that it is in low level code, as you have now well noted. To create the impression that goto is never used is not only not true, but also not fair and misleading to beginner programmers. Hey, writing a game in HLA is easy because of it's High Level added features like a compile time language, a large available HLA library of functions, macros, nested procedures, structures like while ... for ... if ... else if ... else ... etc ...

And ... at some point, a good CS student may just want to know ... just how it is ... that all those nice high level structures are designed and built up from low level code ... :)

This post has been edited by David W: 24 May 2012 - 10:25 AM

Was This Post Helpful? 0
  • +
  • -

#15 jon.kiparsky  Icon User is offline

  • Pancakes!
  • member icon


Reputation: 7963
  • View blog
  • Posts: 13,581
  • Joined: 19-March 11

Re: GOTO Alternative

Posted 24 May 2012 - 10:21 AM

I only said that I won't be writing a text adventure game in assembly. I'm not into stunt programming. Go ahead and write it in assembly if you like, it's good exercise. But you're only likely to do it once. Greenspun's tenth has a few corrollaries, one of which is that you can write anything in a low-level language, but it will generally require that you write a high-level language in the process.

In this case, if you write your zork-alike in HLA, you're going to reinvent a lot of wheels in the process, and if you write them correctly then your actual game code won't ever call an unrestricted goto, because you'll have wrapped the gotos in suitably restrictive routines that insulate you from the hazards of random skipping through the code.

That's not a bad thing to do. It's totally mental, but that's not a bad thing. :)
Was This Post Helpful? 0
  • +
  • -

  • (5 Pages)
  • +
  • 1
  • 2
  • 3
  • Last »