Goto or not goto? (Was: Re: loops in general)

/32767 tif at commlab1..austin.ibm.com
Sat May 5 04:20:15 AEST 1990


In article <12866 at ulysses.att.com> ggs at ulysses.att.com (Griff Smith) writes:
>How do you plan to debug your state machine?  If you have it filled
>with gotos, you have to follow each state transition the hard way.  If
>you use a switch on a state variable, you get to add code between the
>`for (;;)' and the switch to log state transitions, look for strange
>transitions, etc.  I think you're doing a disservice to mortals to
>encourage them to use idioms that are only manageable by higher forms of
>life.

Consider the following:

	#ifdef DEBUG
	#define STATE(x)	case x
	#define TO_STATE(x)	{state=x;break;}
	int	state;

	for(;;) {
		printf("Going to state %d\n", state);
		switch(state) {
	#else
	#define STATE(x)	lbl##x
	#define TO_STATE(x)	goto lbl##x
	#endif


		STATE(0):
			if (...) {
				...
				TO_STATE(0);
			} else
				TO_STATE(5);
		STATE(5):
			if (blah)
				TO_STATE(0);
		...


	#ifdef DEBUG
		}
	}
	#endif

I haven't tried compiling it and I don't know if I used the ## operator
correctly but I think you get the drift.  Now I put to you the question,
does this code suffer from the minuses of "goto" or have the advantages
of the "switch"?  I'm not saying I would write the code like this but
I think I'll let all of you think about how the previously stated pros
and cons apply to this code fragment.  (BTW, break won't work right easily
inside nested control structures.)

Paul Chamberlain
tif at doorstop.austin.ibm.com
tif at commlab1.austin.ibm.com
sc30661 at ausvm6



More information about the Comp.lang.c mailing list