By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
459,200 Members | 1,725 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 459,200 IT Pros & Developers. It's quick & easy.

what's the prob with goto

P: n/a
i m new to the C world...

i ve been told by my instructors not to use goto stmt..
but no one could give me a satisfactory answer as to why it is so..

plz help me out of this dilemma, coz i use a lot of goto in my codes....

Nov 15 '05 #1
Share this Question
Share on Google+
28 Replies


P: n/a
Even though goto were not used directly, but they are implicitly part
of control constructs of a programming lang.

gotos would reduce the redability of the program. If the programming
spanning across pages, it owuld be really difficult to understand the
programs with gotos.

Nov 15 '05 #2

P: n/a
Vishal Naidu said:
i m new to the C world...

i ve been told by my instructors not to use goto stmt..
A wise student obeys his instructors unless he knows them to be wrong.
but no one could give me a satisfactory answer as to why it is so..
Not all instructors understand the advice they give. That doesn't
necessarily mean it is bad advice.
plz help me out of this dilemma, coz i use a lot of goto in my codes....


The problem is that goto doesn't scale well. The more you use it, the harder
your programs will be to maintain, because the flow of control of your
program becomes harder to read. This phenomenon is known as "spaghetti
code", and with good reason.

In many organisations, goto is actually banned altogether. So it's a good
idea to learn how to program without it. Once you have done so, you'll
wonder what you ever saw in it.
--
Richard Heathfield
"Usenet is a strange place" - dmr 29 July 1999
http://www.cpax.org.uk
Email rjh at the above domain

Nov 15 '05 #3

P: n/a

Vishal Naidu wrote:
i m new to the C world...

i ve been told by my instructors not to use goto stmt..
but no one could give me a satisfactory answer as to why it is so..

plz help me out of this dilemma, coz i use a lot of goto in my codes....


Bad structured code is orders of magnitude easier to debug and maintain
than bad unstructured code.

You shouldn't need to use goto very often. One problem with using goto
is that it can destroy the ability to debug code by inspection. It's
not so much the goto itself that's the problem, but rather than the
uncertainty introduced in the code around the target of the goto. For
instance, given the code fragment:

i = 7;
label: printf("%d\n", i);

What value gets printed for any particular path of execution? Until I
account for every instance of "goto label;", I don't know. I have to
trace all possible paths of execution before I can say with any
confidence what gets printed under what conditions. This makes code
harder to debug and maintain. God forbid I have to make any changes,
because I can't say with any confidence that any change will not
inadvertantly affect *some* path of execution.

The story I like to tell is one program I stumbled across early in my
career written by an electrical engineer. A 5000-line main() function,
with something 15 gotos, some of which branched forward, some backward.
It took my co-worker two full weeks to figure out how the damn thing
actually worked. We were tasked with improving performance of the app,
but anything we did simply broke the code. We finally recommended that
the customer just buy faster hardware; it would be cheaper than the
effort to make the code faster would cost.

Now, that particular application was pathological beyond the use of
gotos, but they made a bad situation impossible. Had the code been
somewhat structured, we probably could have made some improvements.

Gotos are useful in a limited set of circumstances, like when you need
to break out of a deeply nested loop, or need to make sure some cleanup
code runs before exiting a routine. But they should not replace
control structures like if-else , for, while, do-while, or switch
statements.

If you're going to use a goto, make sure you branch forward *only*, and
that you do not branch into a block.

Nov 15 '05 #4

P: n/a
Richard Heathfield wrote:
The problem is that goto doesn't scale well. The more you use it, the harder
your programs will be to maintain, because the flow of control of your
program becomes harder to read. This phenomenon is known as "spaghetti
code", and with good reason.

In many organisations, goto is actually banned altogether.


<snip>

But that's okay, because you can achieve similar functionality with
a for loop, a switch statement and liberal application of control
variables. <g>

--
imalone
Nov 15 '05 #5

P: n/a
-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1

Vishal Naidu wrote:
i m new to the C world...

i ve been told by my instructors not to use goto stmt..
but no one could give me a satisfactory answer as to why it is so..

plz help me out of this dilemma, coz i use a lot of goto in my codes....


Please read "Goto Statement Considered Harmfull" by Dr. Dijkstra, in the
"Communications of the ACM". You can find a public version of this paper at
http://www.acm.org/classics/oct95/
- --
Lew Pitcher
IT Specialist, Enterprise Data Systems,
Enterprise Technology Solutions, TD Bank Financial Group

(Opinions expressed are my own, not my employers')
-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.2.4 (MingW32)

iD8DBQFDFu44agVFX4UWr64RArKPAJ9XQL0H+A5gRyx3qECnM3 8veR4RjACeIdks
lhUo4XErlOIavJP/3iqLmQk=
=j7B8
-----END PGP SIGNATURE-----
Nov 15 '05 #6

P: n/a
ajm
Vishal,

John's point about goto into a block is real important, for example if
you skip past the initialisation of certain local variables then the
results can be "undefined" - e.g., static local variables. The C
reference manual (and doubtless other publications) make specific note
of this issue so you have been warned ;)

ajm.

Nov 15 '05 #7

P: n/a
ajm wrote:
Vishal,

John's point about goto into a block is real important, for example if
you skip past the initialisation of certain local variables then the
results can be "undefined" - e.g., static local variables. The C
reference manual (and doubtless other publications) make specific note
of this issue so you have been warned ;)


The warning is good, but the detail is not: a static
variable cannot be uninitialized, and furthermore its
initialization occurs before the program starts and thus
does not depend on the run-time flow of execution. The
problem ajm mentions afflicts auto and register variables,
but not statics.

--
Eric Sosman
es*****@acm-dot-org.invalid
Nov 15 '05 #8

P: n/a
ajm
apologies! yes of course that is what I meant to say (statics are
handled entirely differently as Eric points out)

Nov 15 '05 #9

P: n/a
"Vishal Naidu" writes:
i m new to the C world...

i ve been told by my instructors not to use goto stmt..
but no one could give me a satisfactory answer as to why it is so..

plz help me out of this dilemma, coz i use a lot of goto in my codes....


If the instructor had taught the course properly you wouldn't be using a lot
of gotos, because you wouldn't even no the stmt existed till the last day of
the course.
Nov 15 '05 #10

P: n/a
Richard Heathfield <in*****@invalid.invalid> writes:
Vishal Naidu said:
i m new to the C world...

i ve been told by my instructors not to use goto stmt..


A wise student obeys his instructors unless he knows them to be wrong.


A wise student seeks to know *why*, not merely *what*.
but no one could give me a satisfactory answer as to why it is so..


Not all instructors understand the advice they give. That doesn't
necessarily mean it is bad advice.


An instructor that cannot justify his own advice is likely a bad
instructor.
--
"When I have to rely on inadequacy, I prefer it to be my own."
--Richard Heathfield
Nov 15 '05 #11

P: n/a
Lew Pitcher <Le*********@td.com> writes:
Please read "Goto Statement Considered Harmfull" by Dr. Dijkstra, in the
"Communications of the ACM". You can find a public version of this paper at
http://www.acm.org/classics/oct95/


For a more balanced point of view, see Knuth's _Structured
Programming with go to Statements_.
--
int main(void){char p[]="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuv wxyz.\
\n",*q="kl BIcNBFr.NKEzjwCIxNJC";int i=sizeof p/2;char *strchr();int putchar(\
);while(*q){i+=strchr(p,*q++)-p;if(i>=(int)sizeof p)i-=sizeof p-1;putchar(p[i]\
);}return 0;}
Nov 15 '05 #12

P: n/a
Richard Heathfield wrote
(in article
<df**********@nwrdmz02.dmz.ncs.ea.ibs-infra.bt.com>):
Vishal Naidu said:
i m new to the C world...

i ve been told by my instructors not to use goto stmt..
A wise student obeys his instructors unless he knows them to be wrong.


And a brilliant student will /still/ want to know the reasons
behind the advice.
but no one could give me a satisfactory answer as to why it is so..


Not all instructors understand the advice they give. That doesn't
necessarily mean it is bad advice.


True, but not a justification for blindly following it. There
are probably professors that show the use of void main() as well
in their examples.
plz help me out of this dilemma, coz i use a lot of goto in my codes....


The problem is that goto doesn't scale well. The more you use it, the harder
your programs will be to maintain, because the flow of control of your
program becomes harder to read. This phenomenon is known as "spaghetti
code", and with good reason.


Agreed.
In many organisations, goto is actually banned altogether.
Very true, thanks in no small part to a famous paper on the
subject, entitled "Go To Statement Considered Harmful", written
by Dijkstra and published in ACM way back in March of 1968.
That's how long this debate has been raging. There are also
similar, but not identical copies of this paper with a different
title "A Case against the GO TO Statement" what appeared as 'EWD
Manuscripts'.

Of course, there are also those that thing that he overstated
the case, resulting in a lot of people blindly following the
admonition without understanding why. Ironic, that.

See also, "Flow Diagrams, Turing Machines, and Languages with
only two formation rules," C. Bohm & G. Jacopini, , ACM May
1966.

David Tribble does a good job analyzing and commenting on it
here:
http://david.tribble.com/text/goto.html
So it's a good idea to learn how to program without it. Once you
have done so, you'll wonder what you ever saw in it.


Possibly. There are cases where it is difficult to avoid, and
might produce a more readable result than some attempt to not
use it. The use of setjmp/longjmp isn't much different either.

In some deeply nested loops (which I don't generally recommend)
it may also be necessary.

I would say that the goto statement is best avoided, but to not
necessarily adopt the view that it /must/ be avoided in all
cases. Blindly following good advice may be slightly better
than blindly following bad advice, but that doesn't mean blindly
following anything is a good idea.
--
Randy Howard (2reply remove FOOBAR)

Nov 15 '05 #13

P: n/a
In article <11**********************@g49g2000cwa.googlegroups .com>,
"Vishal Naidu" <na*********@gmail.com> wrote:
i m new to the C world...

i ve been told by my instructors not to use goto stmt..
but no one could give me a satisfactory answer as to why it is so..

plz help me out of this dilemma, coz i use a lot of goto in my codes....


1. Using corrupted English like "plz" and "coz" is considered to be
absolutely uncool amongst most readers here.

2. Not using goto's will help you become a better programmer. Whether
your instructor can explain why doesn't make a difference.

3. At some point you will hopefully be wise enough to recognise the rare
situation when using "goto" is better than not using "goto". But if you
have to ask whether to use it or not, then don't use it.
Nov 15 '05 #14

P: n/a
In article <11**********************@g49g2000cwa.googlegroups .com>,
Vishal Naidu <na*********@gmail.com> writes
i m new to the C world...

i ve been told by my instructors not to use goto stmt..
but no one could give me a satisfactory answer as to why it is so..

plz help me out of this dilemma, coz i use a lot of goto in my codes....


This came up on the high-integrity discussion group the other day. It
was discussed by two leading and well known people in safety critical
software.

Apparently there is no empirical evidence that goto is harmful. There
was one study but I think it was not seen as valid. Though it did show
that bug count was proportional to the number of gotos!

The problem is more subtle. You can recognise good or "clean" design in
physical objects but can't quantify why. Quality is recognisable but
difficult to quantify. Software is, like painting, sculpture, music
part technique (that has to be practised, masters and rigorously
applied) and part art.

Similarly experienced practitioners (like master craftsmen) know/feel
goto is bad but can't really give you a hard and fast mathematical or
solid logical reason.

The can give valid examples but so can the naysayers.

Generally you should use the "normal" flow control statements. If while
do switch.

This implies that you have to think about the design of the code.
Software Engineering is about designing the program. When it is designed
then you write the code.
Remember all entered apprentices need to learn techniques. Often the
need to master these techniques before the reasoning falls into place.
The explanation will not make sense until you have got to the point
where the answer is clear without asking. Before that point the answer
will not make sense.

--
\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\
\/\/\/\/\ Chris Hills Staffs England /\/\/\/\/
/\/\/ ch***@phaedsys.org www.phaedsys.org \/\/\
\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/

Nov 15 '05 #15

P: n/a
In article <ch*********************************@slb-newsm1.svr.pol.co.uk>,
Christian Bau <ch***********@cbau.freeserve.co.uk> wrote:
2. Not using goto's will help you become a better programmer. Whether
your instructor can explain why doesn't make a difference.


Acquiring a frame of mind in which you naturally use some other control
mechanism except in rare cases seems like a good thing.

But if instead you translate the gotos that seem natural to you into
something else, you may just end up producing more buggy code.

I suppose the forced discipline of not using gotos may eventually help
you to acquire the right intuition, but being taught *why* they're
usually bad seems like a more straightforward approach.

-- Richard
Nov 15 '05 #16

P: n/a
Christian Bau wrote:
plz help me out of this dilemma, coz i use a lot of goto in my
codes....


1. Using corrupted English like "plz" and "coz" is considered to be
absolutely uncool amongst most readers here.


Well, what is 'uncool' if not corrupted English? Sure, it's made
several
dictionaries, but then so has 'pls'. ;)

It's not the 'cool' factor that's at issue. It's that such terms
make it that little bit more difficult to read the posts, hence
they reduce the likelyhood of people focusing (or even bothering)
with the question at hand.

OP's should consider plain English communication (at least in clc),
along with actual source code illustrating the problem, as a sound
investment, if not simple courtesy.

--
Peter

Nov 15 '05 #17

P: n/a
Groovy hepcat Richard Heathfield was jivin' on Thu, 1 Sep 2005
09:40:36 +0000 (UTC) in comp.lang.c.
Re: what's the prob with goto's a cool scene! Dig it!
The problem is that goto doesn't scale well. The more you use it, the harder
your programs will be to maintain, because the flow of control of your
program becomes harder to read. This phenomenon is known as "spaghetti
code", and with good reason.


I've said it before and I'll say it again. Meatball programmers
write spaghetti code. :)

--

Dig the even newer still, yet more improved, sig!

http://alphalink.com.au/~phaywood/
"Ain't I'm a dog?" - Ronny Self, Ain't I'm a Dog, written by G. Sherry & W. Walker.
I know it's not "technically correct" English; but since when was rock & roll "technically correct"?
Nov 15 '05 #18

P: n/a
Ben Pfaff said:
Richard Heathfield <in*****@invalid.invalid> writes:
Vishal Naidu said:
i m new to the C world...

i ve been told by my instructors not to use goto stmt..


A wise student obeys his instructors unless he knows them to be wrong.


A wise student seeks to know *why*, not merely *what*.


ITYM A wiser student. I was working on the basis that most students are not
as wise as all that. ;-)

--
Richard Heathfield
"Usenet is a strange place" - dmr 29 July 1999
http://www.cpax.org.uk
Email rjh at the above domain

Nov 15 '05 #19

P: n/a
Le 01-09-2005, Ben Pfaff <bl*@cs.stanford.edu> a écrit*:
Richard Heathfield <in*****@invalid.invalid> writes:
Vishal Naidu said:
but no one could give me a satisfactory answer as to why it is so..


Not all instructors understand the advice they give. That doesn't
necessarily mean it is bad advice.


An instructor that cannot justify his own advice is likely a bad
instructor.


Not the best one, yes, but to the worst.
I prefer "no justification" to "wrong justification".

Marc Boyer
Nov 15 '05 #20

P: n/a
Christian Bau <ch***********@cbau.freeserve.co.uk> wrote:
1. Using corrupted English like "plz" and "coz" is considered to be
absolutely uncool amongst most readers here.


Especially by one Joona Palaste, whom I mention solely for the purpose
of wondering where he's been lately.

--
Christopher Benson-Manica | I *should* know what I'm talking about - if I
ataru(at)cyberspace.org | don't, I need to know. Flames welcome.
Nov 15 '05 #21

P: n/a
Christopher Benson-Manica wrote
(in article <df**********@chessie.cirr.com>):
Christian Bau <ch***********@cbau.freeserve.co.uk> wrote:
1. Using corrupted English like "plz" and "coz" is considered to be
absolutely uncool amongst most readers here.


Especially by one Joona Palaste, whom I mention solely for the purpose
of wondering where he's been lately.


Heathfield Syndrome
(patent pending)
--
Randy Howard (2reply remove FOOBAR)

Nov 15 '05 #22

P: n/a
On Thu, 01 Sep 2005 08:04:08 -0400, Lew Pitcher wrote:
-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1

Vishal Naidu wrote:
i m new to the C world...

i ve been told by my instructors not to use goto stmt..
but no one could give me a satisfactory answer as to why it is so..

plz help me out of this dilemma, coz i use a lot of goto in my codes....


Please read "Goto Statement Considered Harmfull" by Dr. Dijkstra, in the
"Communications of the ACM". You can find a public version of this paper at
http://www.acm.org/classics/oct95/


Although I'm not sure that paper would mean much to somebody just
starting to learn programming.

Programming paradigms like structured programming, functional programming,
object oriented programming and so on are really all about approaches to
encapsulation. Even a program of 100 lines can can contain a lot of
complexity, as program size increases so does complexity. But the human
mind can only deal with a fairly small amount of complexity at a time. So
we try to manage complex software by arranging it into units that can be
described and thought about simply, so we don't have to consider the
complexity of the whole program all at once. Functions in C are a very
obvious construct for doing this. But there is also complexity within the
code of a function body and it can also be managed. C is a block
structured language and statements can be grouped together in {}'s and
treated like a single entity. This is an, albeit simple, form of
encapsulation. A loop like:

for (.....) {
loop body
}

can also be considered as a single entity whith a purpose that can
hopefully be described and thought about simply. Perhaps less obviously
that is also true for a conditional statement like

if (test) {
code
} else {
code
}

if well designed it can be considered as a single entity with a simple
purpose. The thing about all of these constructs is that they are well
delineated, they have a clear start and end and hopefully clear and simple
entry and exit conditions. When that's the case they are easy to think
about and fit together in the larger whole.

Problems with gotos are:

1. the lack of control on them. You can jump to anywhere in the function
whch tends to destroy the sort of structure I talk about above that
makes code easier to think about.

2. Being so general, a goto tells you very little about the purpose it is
being put to. For example a for loop tells you that you have a loop, the
control expressions give well defined information about the loop in a well
defined place that is easy to find, and it is easy to see where the code
for the loop starts and ends. Gotos give you very little of this.

It is possible to program in a "structured" way using gotos, and this was
a reasonable thing to do in languages that didn't give you alternative
constructs. However it is up to you to make sure the structure of your
code stays clean, goto doesn't give you any help in that respect, and it
still lacks the clues that are helpful to somebody reading the code. So
when structured constructs are available, as they are in C, it is
preferable to use them.

Even so C still provides a goto statement. And there are occasions where
it is useful, but they are rare. Offhand I can think of 3 areas where
using goto can be reasonable: error handling, exiting from nested loops,
and finite state machines.

If you DO ever use a goto you can avoid much of the nastiness by following
the simple rule that a goto should jump forwards and never backwards in
the code. Although finite state machines that use goto are an exception to
this.

Lawrence

Nov 15 '05 #23

P: n/a
In article <pa****************************@netactive.co.uk> ,
Lawrence Kirby <lk****@netactive.co.uk> wrote:
If you DO ever use a goto you can avoid much of the nastiness by following
the simple rule that a goto should jump forwards and never backwards in
the code. Although finite state machines that use goto are an exception to
this.


As is simulation of tail-recursion.

-- Richard

Nov 15 '05 #24

P: n/a
ri*****@cogsci.ed.ac.uk (Richard Tobin) writes:
In article <pa****************************@netactive.co.uk> ,
Lawrence Kirby <lk****@netactive.co.uk> wrote:
If you DO ever use a goto you can avoid much of the nastiness by following
the simple rule that a goto should jump forwards and never backwards in
the code. Although finite state machines that use goto are an exception to
this.


As is simulation of tail-recursion.


Hmm. Do you have an example of using a goto to simulate
tail-recursion that wouldn't be better implemented as an explicit
loop?

--
Keith Thompson (The_Other_Keith) ks***@mib.org <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <*> <http://users.sdsc.edu/~kst>
We must do something. This is something. Therefore, we must do this.
Nov 15 '05 #25

P: n/a
In article <ln************@nuthaus.mib.org>,
Keith Thompson <ks***@mib.org> wrote:
Hmm. Do you have an example of using a goto to simulate
tail-recursion that wouldn't be better implemented as an explicit
loop?


I'm not sure I have one where using goto is better as an implementation
of the function per se, but it's better as an expression of the fact
that I am writing it as a tail-recursive function and have to get
around the limitation that compilers won't necessarily compile
tail-recursive functions to something that works.

You might say that it's better to stick to idioms that are directly
supported by C, but sometimes I prefer to impose my will on the laguage.

-- Richard
Nov 15 '05 #26

P: n/a
In article <ln************@nuthaus.mib.org>,
Keith Thompson <ks***@mib.org> wrote:


ri*****@cogsci.ed.ac.uk (Richard Tobin) writes:
In article <pa****************************@netactive.co.uk> ,
Lawrence Kirby <lk****@netactive.co.uk> wrote:
If you DO ever use a goto you can avoid much of the nastiness by following
the simple rule that a goto should jump forwards and never backwards in
the code. Although finite state machines that use goto are an exception to
this.


As is simulation of tail-recursion.


Hmm. Do you have an example of using a goto to simulate
tail-recursion that wouldn't be better implemented as an explicit
loop?


The Ackerman function comes to mind.

http://mathworld.wolfram.com/AckermannFunction.html

Perhaps I am over-simplifying, but I think that any recursive
function that (a) is otherwise amenable to TRE and (b) calls
itself from multiple places, not just the "end" is not well
served by a loop. Frankly, I don't think it is well-served by a
goto either. It may simply be that there is a a very, very
small class of algorithms that C is not ideal for.

Related to this kind of multi-point recursion is:

http://mathworld.wolfram.com/TAKFunction.html

A long time ago, a scheme programmer and I had a disagreement
over a benchmark component based on TAK. Scheme liberally
applies TRE and handily beat gcc. I tuned the C code not by
TRE, but by hoisting the if's up one level of recursion.
This kept the code readable and recognizable, and didn't involve
goto's or extra loops.

Lest I seem pseudo-intellectual, let me disclaim that I don't
really understand the above functions or their applicability;
I just coded them and optimized them in C, which is something
I know I can handle. :-)
Nov 15 '05 #27

P: n/a

In article <zeFTe.5979$mH.601@fed1read07>, an******@example.com (Anonymous 7843) writes:
It may simply be that there is a a very, very
small class of algorithms that C is not ideal for.


Based on Greg Chaitin's work, I'd guess that it's actually a very,
very large class of algorithms. Fortunately, nearly all are useless.

--
Michael Wojcik mi************@microfocus.com

Most people believe that anything that is true is true for a reason.
These theorems show that some things are true for no reason at all,
i.e., accidentally, or at random. -- G J Chaitin
Nov 15 '05 #28

P: n/a
In article <df*********@news3.newsguy.com>,
Michael Wojcik <mw*****@newsguy.com> wrote:

In article <zeFTe.5979$mH.601@fed1read07>, an******@example.com
(Anonymous 7843) writes:
It may simply be that there is a a very, very
small class of algorithms that C is not ideal for.


Based on Greg Chaitin's work, I'd guess that it's actually a very,
very large class of algorithms. Fortunately, nearly all are useless.


I'm hoping he'll stumble upon a P=NP proof somewhere along
the way. It sure isn't anywhere else.
Nov 15 '05 #29

This discussion thread is closed

Replies have been disabled for this discussion.