473,770 Members | 2,120 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

when GOTO makes sense.

K&R pg.66 describes two situations when using goto makes sense. Has
anyone here come across situations where using goto provided the most
elegant solution.

--
http://www.kashmiri-pandit.org/atrocities/index.html

Nov 13 '05 #1
45 2727
Debashish Chakravarty wrote:
K&R pg.66 describes two situations when using goto makes sense. Has
anyone here come across situations where using goto provided the most
elegant solution.


Yes. Sometimes when...

1. There is code with a lot of resource allocation and/or semaphores
being held and...

2. There are many potential points of failure and...

3. The resources need to be freed in a very precise order on failure...

.... goto usage can be the most elegant solution.
Because of #1 it's very important to prevent resource leaks and/or
deadlocks. #2 makes it problematic and error prone (for maintenence
programmers) to do:

if(error_condit ion) {
free(a);
free(b);
unlock(c);
unlock(d);
free(e);
return -1;
}

at every point where a failure may occur (there may be 10 of them, and
each may be subtly different). It may be better to have something like:
(again, only a contrived example, assuming a, b, c, e are initialize
to NULL, etc)
if(error_condit ion)
goto err;

/*...*/

err:
/* Order important !! */
if(a) free(a);
if(b) free(b);
if(c) free(c);
unlock(c); /* must unlock c before d */
unlock(d); /* must unlock d before free(e) */
if(e) free(e);
return -1;
}
Mark F. Haigh
mf*****@sbcglob al.net

Nov 13 '05 #2
Debashish Chakravarty <de********@yah oo.com> wrote:
K&R pg.66 describes two situations when using goto makes sense. Has
anyone here come across situations where using goto provided the most
elegant solution.


The classic case is breaking out of a nested loop from the inside.
While people who hate goto for some reason despise such things and
prefer having extra if-checks to account such a condition, its slower,
and just makes your code more complicated.

But another interesting case is with state machines. While the
classic implementation of a state matchine is to simply put a switch
statement inside of a while (1) { ... } loop, this has a drawback of
requiring the switch statement to be execute on every state change (on
modern processors this is much slower than direct gotos.) But as an
alternative, one could simply have one switch statement and rather
than breaks at the end of each case block, simply have gotos to the
blocks that represent the state transition. You have to have labels
that are redundant with the case ...: statements, however this
solution is much faster, and doesn't require that you maintain a state
variable (since the state itself would be redundant with the case
clause that was being executed at any one time) for all states (just
entry and exit of the state machine.)

Finally sometimes its best, for performance reasons to start a loop in
the middle of the body of the loop rather than a start. So you have a
goto just before your do {...} while or for() loop to enter in the
middle of it.

These are probably the most interesting marginal cases where using
goto is the best solution in the C language. The problem is that
there are many other uses of goto which are really really bad. So
much so that people have railed against its usage, and will actually
choose not to do so in any situation. They will lose performance
and/or make their code complicated in all of the above cases. So this
*should* make a good case for improving improving the language so that
these operations can be done *without* goto (for example <break n;> to
jump out of n nested blocks, and <continue case ___;> to jump to a
case within the nearest enclosing switch scope.) However, I don't
know if the C standards committee is open to suggestions such as
these.

--
Paul Hsieh
http://www.pobox.com/~qed/
http://bstring.sf.net/
Nov 13 '05 #3
On Sat, 29 Nov 2003 06:00:40 -0800, Paul Hsieh wrote:

But another interesting case is with state machines. While the
classic implementation of a state matchine is to simply put a switch
statement inside of a while (1) { ... } loop, this has a drawback of
requiring the switch statement to be execute on every state change (on
modern processors this is much slower than direct gotos.) But as an
alternative, one could simply have one switch statement and rather
than breaks at the end of each case block, simply have gotos to the
blocks that represent the state transition. You have to have labels
that are redundant with the case ...: statements, however this
solution is much faster, and doesn't require that you maintain a state
variable (since the state itself would be redundant with the case
clause that was being executed at any one time) for all states (just
entry and exit of the state machine.)


Hmm, I've always implemented state machines with function pointers, like
so:
.... in the header:
typedef void * (*state) (int);
.... in main.c:
while (ch = getnewinput()) {
current = (state)(*curren t)(ch);
}
}
.... example state: ( this is a very simple DFA )
void *
green (int input) {
switch (input) {
case 'A':
printf("LIGHTS OFF\n");
return &other;
break;
case 'B':
printf("LIGHTS OFF\n");
return &initial;
break;
}
}

Of course, casting function pointers to void and back can lead to
undefined behavior on certain architectures (though I've verified that
this code works on x86 and PPC). But doesn't this seem like a better
solution (and definitely more functional, seeing as it basically emulates
the workings of a functional language), than using gotos?

--
Mike's Patented Blocklist; compile with gcc:

i=0;o(a){printf ("%u",i>>8*a&25 5);if(a){printf (".");o(--a);}}
main(){do{o(3); puts("");}while (++i);}

Nov 13 '05 #4
In article <pa************ *************** @spamblocked.co m>,
"Michael B." <us*****@spambl ocked.com> wrote:
Of course, casting function pointers to void and back can lead to
undefined behavior on certain architectures (though I've verified that
this code works on x86 and PPC). But doesn't this seem like a better
solution (and definitely more functional, seeing as it basically emulates
the workings of a functional language), than using gotos?


It leads to undefined behavior, that's it. So that makes it in the eyes
of most people a very bad solution, definitely worse than using goto.

It also mixes up "states" and "implementa tion of code to handle the
action in a given state". Each of your functions doesn't return a state,
it returns a pointer to the code to be executed in that state.

And it adds significantly to the number of lines of code to be written.
In most state machines, the code for each state is quite trivial, so
adding a few lines for every state adds significantly to the lines of
code.
Nov 13 '05 #5
"Mark F. Haigh" <mf*****@sbcglo bal.ten> wrote in message news:<zF******* ************@ne wssvr25.news.pr odigy.com>...
Debashish Chakravarty wrote:
anyone here come across situations where using goto provided the most
elegant solution.

Yes. Sometimes when...
2. There are many potential points of failure and...
3. The resources need to be freed in a very precise order on failure...


These gotos may sometimes be avoided by replacing
if (! step7())
goto backout7;
if (! step8())
goto backout8;
...
with
if (step7()) {
if (step8()) {
...
}
}
but the cure may be worse than the disease
if there are many levels of nesting.

Another frequent case where goto is better than the alternative is
for (Search; unfinished;) {
for (Subsearch; unfinished;) {
if (WE_WON) {
celebrate();
goto persevere;
}
}
}
lament();
persevere: ;

(Even when loops are not nested, a ``break'' is not quite
enough to avoid this ``goto.'')

I use very few gotos in *final* code, but when cranking out
fresh code, I sometimes write ``goto start_over'' and then decide
later, when I see the full logic, whether to rewrite the loop as
``do'', ``while'' or ``for.'' (In other words, the goto-less
version will be more *readable*, but the *goto* is more *writable*.)

Finally, let me mention my Favorite Goto (tm):
http://freepages.genealogy.rootsweb....ech/dbldum.htm

If one needs to make major changes to the Favorite Goto program,
getting rid of the goto might be the first step, but as is,
it possesses, IMO, a beautiful elegance no non-GOTO version
will have. Can you construct a goto-less equivalent that is
in the same ballpark for speed and readability?

(I have posted the Favorite Goto before on Usenet, receiving
some suggestions which made no sense. Please code, compile and
test your version before sending it to me.)

James
Nov 13 '05 #6
In <3F************ **@yahoo.com> Debashish Chakravarty <de********@yah oo.com> writes:
K&R pg.66 describes two situations when using goto makes sense. Has
anyone here come across situations where using goto provided the most
elegant solution.


'Elegant' is in the eye of the beholder. I prefer to speak in terms of
readable code. The code readability decreases exponentially when the
number of nested control structures increases linearly. If a goto can
avoid an additional nesting level, than that goto is probably a "good"
goto. Of course, this is not the only technique for minimising the number
of nested control structures in a function, but one shouldn't
automatically discard it on religious grounds.

Dan
--
Dan Pop
DESY Zeuthen, RZ group
Email: Da*****@ifh.de
Nov 13 '05 #7


James Dow Allen wrote:

<snip>
Finally, let me mention my Favorite Goto (tm):
http://freepages.genealogy.rootsweb....ech/dbldum.htm

If one needs to make major changes to the Favorite Goto program,
getting rid of the goto might be the first step, but as is,
it possesses, IMO, a beautiful elegance no non-GOTO version
will have. Can you construct a goto-less equivalent that is
in the same ballpark for speed and readability?


This MAY (or may not) be the most efficient piece of code on the planet,
but this has to be some of the worst code I've ever seen for
readability. In particular, jumping back and forth between the bodies of
2 separate pairs of nested "for" loops using "goto"s is horrible, and
then having compound conditions like this in a loop:

for (tnum = won = success = 0;
success ? ++won < need : won + ohsize >= need + tnum;
tnum++, P++, success = IS_CONT(pwin)) {

is just ridiculuous too.

By the way, the program hangs on the second sample input provided on the
web site. I would debug it, but I don't want to take the time to
understand it ;-). Ditto for providing a non-goto alternative.

I'm not 100% against gotos, I've just never seen code that uses gotos
that I personally find more readable than the equivalent without gotos.
I recently wrote a short (200 lines or so) program using gotos just to
see if I could learn to appreciate the benefits wrt error-handling, but
once the error-handling became even moderatly complex (i.e. realisitc!)
the initial simplicity afforded by the gotos fell away. I looked at your
code hoping to learn a good way to use goto for readability.

Ed.

Nov 13 '05 #8
On Mon, 1 Dec 2003 05:13:10 UTC, jd*********@yah oo.com (James Dow
Allen) wrote:
I use very few gotos in *final* code, but when cranking out
fresh code, I sometimes write ``goto start_over'' and then decide
later, when I see the full logic, whether to rewrite the loop as
``do'', ``while'' or ``for.'' (In other words, the goto-less
version will be more *readable*, but the *goto* is more *writable*.) Finally, let me mention my Favorite Goto (tm):
http://freepages.genealogy.rootsweb....ech/dbldum.htm
Looks more obscure than needed. A better structure is required.

Use functions to encapsulate details from the flow.
Using the the same functions would remove any need for goto as side
effect.
You've written some loops looking exactly identical. Buildng fuctions
would remove the details from the flow and lets them reused.

Programming starts with design, not hacking.
A well designed program has not a single function but many of them,
each not longer than about 50 lines, doing one specific task. Not
more, not less.

A task gets splitted in What is to do and how is it done. This makes
debugging more easy, helps to understund the flow and is at least more
readable as such a hack as you'd produced.
If one needs to make major changes to the Favorite Goto program,
getting rid of the goto might be the first step, but as is,
it possesses, IMO, a beautiful elegance no non-GOTO version
will have. Can you construct a goto-less equivalent that is
in the same ballpark for speed and readability?


A side effect would be that there is no goto in the whole program.
That is because the need of goto gets superflous by design.

--
Tschau/Bye
Herbert

To buy eComStation 1.1 in germany visit http://www.pc-rosenau.de

Nov 13 '05 #9
On Fri, 28 Nov 2003 22:08:10 -0500, Debashish Chakravarty
<de********@yah oo.com> wrote:
K&R pg.66 describes two situations when using goto makes sense. Has
anyone here come across situations where using goto provided the most
elegant solution.


Yes.

--
Al Balmer
Balmer Consulting
re************* ***********@att .net
Nov 13 '05 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

25
4651
by: BOOGIEMAN | last post by:
I've just finished reading Python turtorial for non-programmers and I haven't found there anything about some usefull commands I used in QBasic. First of all, what's Python command equivalent to QBasic's "goto" ? Secondly, how do I clear screen (cls) from text and other content ? And last, how do I put program to wait certain amount of seconds ? If I remeber correctly I used to type "Wait 10" and QBasic waits 10 seconds before proceeding...
36
6740
by: Michael | last post by:
Hi, I know I know its notoriously bad! I don't want to use it. I was wondering, does it still exist? If it does, I really don't understand how!? like what happens if you just goto halfway through a function (no objects properly constructed!) , or a constructor itself?? Just intrigued!! Mike
5
1795
by: deko | last post by:
I've heard it said that you only want to use a number (e.g. integer, long, etc.) if you are going to do calculations or some kind of math with it. Is this true? For example, I run a validate routine that checks an address entry - if something's missing in the entry, the code does different things based on what is missing, indicated my a 2 or a 3 - integer values. Should I use string data types here? Does it matter? Public Sub...
51
13388
by: WindAndWaves | last post by:
Can anyone tell me what is wrong with the goto command. I noticed it is one of those NEVER USE. I can understand that it may lead to confusing code, but I often use it like this: is this wrong????? Function x select case z
17
2317
by: Mike Hofer | last post by:
While I'd toyed with C, C++, and Java over the last 20 years or so, my principal language has been BASIC, QBASIC, then Visual Basic, and finally Visual Basic .NET. But lately, I've been using C# and I absolutely *love* it. It makes me think more about what I'm doing it before I just spew code into the editor. I'm writing better code than ever. The only thing so far that I don't like about it is the switch construct. I can't do this:
77
4039
by: M.B | last post by:
Guys, Need some of your opinion on an oft beaten track We have an option of using "goto" in C language, but most testbooks (even K&R) advice against use of it. My personal experience was that goto sometimes makes program some more cleaner and easy to understand and also quite useful (in error handling cases). So why goto is outlawed from civilized c programmers community. is there any technical inefficiency in that.
8
2258
by: cat | last post by:
I had a long and heated discussion with other developers on my team on when it makes sense to throw an exception and when to use an alternate solution. The .NET documentation recommends that an exception should be thrown only in exceptional situations. It turned out that each of my colleagues had their own interpretation about what an "exceptional situation" may actually be. First of all, myself I’m against using exceptions extensively,...
34
26647
by: electrician | last post by:
Perl has it, Basic has it, Fortran has it. What is so difficult about creating a goto command for JavaScript. Just set up a label and say go to it.
59
5065
by: raashid bhatt | last post by:
why are GOTO's not used they just a simple JMP instructions what's bad about them
0
9618
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
1
10038
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9906
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
1
7456
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6712
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5354
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5482
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4007
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
3
2850
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.