Why is goto bad?

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

140 Replies - 8130 Views - Last Post: 22 July 2011 - 04:27 AM Rate Topic: -----

#1 hulla  Icon User is offline

  • Writing Lines


Reputation: 49
  • View blog
  • Posts: 732
  • Joined: 05-March 11

Why is goto bad?

Post icon  Posted 07 July 2011 - 05:48 AM

Why is goto bad?

<mod edit> Featured: I know this topic gets covered and recovered and hashed out etc. etc. etc. but the discussion below seems pretty interesting so I will feature it to see what we come up with in this edition of "Goto: Programming Hell or Dogmatic Purgatory" -- NickDMax</mod edit>

Is This A Good Question/Topic? 3
  • +

Replies To: Why is goto bad?

#2 PlasticineGuy  Icon User is offline

  • mov dword[esp+eax],0
  • member icon

Reputation: 281
  • View blog
  • Posts: 1,436
  • Joined: 03-January 10

Re: Why is goto bad?

Posted 07 July 2011 - 05:51 AM

Goto is bad because it can cause horribly unreadable code.
#include <iostream>
int main ()
{
    goto hello;
input:
    std::string name;
    std::cin >> name;
    goto print;
prompt:
    std::cout << "Enter your name:\n";
    goto input;
end:
    std::cin.clear();
    std::cin.ignore();
    std::cin.get();
    return 0;
hello:
    std::cout << "Hello!\n";
    goto prompt;
print:
    std::cout << name << "\n";
    goto end;
}
It's just generally a bad idea. It's a relic from assembly language where it is the only (efficient) way to use loops.
http://forum.codecal...oto-so-bad.html This forum has an interesting discussion. Basically every loop construct can be used to write faster, cleaner and safer code, except for a few specific cases. So it's not intrinsically bad but is often unnecessarily and incorrectly used.

An interesting view is that "once people start using goto, they never stop."

This post has been edited by PlasticineGuy: 07 July 2011 - 05:55 AM

Was This Post Helpful? 3
  • +
  • -

#3 CTphpnwb  Icon User is online

  • D.I.C Lover
  • member icon

Reputation: 3001
  • View blog
  • Posts: 10,393
  • Joined: 08-August 08

Re: Why is goto bad?

Posted 07 July 2011 - 05:52 AM

It causes confusion. Imagine you were reading a book and instead of using a book mark you kept track of the paragraph number that you had read up to. Would that be a good thing?

Code should be written with readability in mind at all times. Using goto destroys readability.
Was This Post Helpful? 0
  • +
  • -

#4 kiwi_steve  Icon User is offline

  • D.I.C Head

Reputation: 31
  • View blog
  • Posts: 109
  • Joined: 26-September 09

Re: Why is goto bad?

Posted 07 July 2011 - 06:03 AM

View PostPlasticineGuy, on 08 July 2011 - 01:51 AM, said:

An interesting view is that "once people start using goto, they never stop."


I learned to program in BASIC... goto was very cool when I was just beginning. I now do not use it except when doing assembly. I'm the very model of polite OO behaviour these days :)

View PostCTphpnwb, on 08 July 2011 - 01:52 AM, said:

It causes confusion. Imagine you were reading a book and instead of using a book mark you kept track of the paragraph number that you had read up to. Would that be a good thing?


Sounds like the old Steve Jackson/Ian Livingston Fighting Fantasy books I read as a kid :)

Actually, my take on GOTO is that it has a place, like most commands. Used in its place, its fine... used where it shouldn't be, and you have a problem. It could be likened to being naked. Its perfectly ok if you're in the shower, but its just wrong to go down to the supermarket like that.

Ok, so maybe its nothing like being naked at all... but back to the point, it was very handy when I was 11 and all you could get to program on was a ZX81

Steve
Was This Post Helpful? 0
  • +
  • -

#5 baavgai  Icon User is offline

  • Dreaming Coder
  • member icon

Reputation: 5848
  • View blog
  • Posts: 12,707
  • Joined: 16-October 07

Re: Why is goto bad?

Posted 07 July 2011 - 06:11 AM

We hash this one out every so often. Notably here and here.

My short form; there are few languages that require them, like Assembly (JMP) and ancient BASIC. For those, you're stuck with it.

In C and C++, there is simply never a need for goto or a justifiable reason to use it in well organized code. The best excuse I've seen for them in C is old UNIX Networking code, where you have to fall out but also clean up state created in the block. Still, you don't need them, they're just a dirty little shortcut.
Was This Post Helpful? 2
  • +
  • -

#6 Kilorn  Icon User is offline

  • XNArchitect
  • member icon



Reputation: 1356
  • View blog
  • Posts: 3,528
  • Joined: 03-May 10

Re: Why is goto bad?

Posted 07 July 2011 - 06:22 AM

Goto has it's place. As mentioned by baavgai in Assembly, BASIC, and some of the other older languages that aren't used that often anymore, you are stuck with it. Goto is also helpful in UnrealScript when using Unreal Development Kit but even within those languages it has it's place and can still cause some great confusion so it is best to only use it when it is absolutely necessary.
Was This Post Helpful? 0
  • +
  • -

#7 NickDMax  Icon User is offline

  • Can grep dead trees!
  • member icon

Reputation: 2250
  • View blog
  • Posts: 9,245
  • Joined: 18-February 07

Re: Why is goto bad?

Posted 07 July 2011 - 06:32 AM

You know for me letting go of goto is one of the hurdles of becoming a programming. I actually think that beginners should be taught goto (and global variables) and then one can monitor their progress to enlightenment by how sparingly they use it.

Goto and global variables are a lot of freedom. Weeeeeeeee we can do what we want.

but the code that results from this freedom is called "spaghetti code" for a reason. Its like the collection of wires behind your entertainment center. Sure it all makes sense when you first put it together but then you come back and its just a god-awful mess and you get frustrated and you sware that this time you will be "more organized".

Enter "structured programming" -- structured programming is a phrase that is not used very often today but it is the use of the "control structures" and functions to control the flow of logic in a program. Structured programming is the antithesis of goto. Once upon a time it was considered the height of programming enlightenment. Now the expression is hardly ever used and to be honest "structured programming" itself is hardly considered very enlightened given Object Oriented Programming, Generic Programming, and the "new" functional programming techniques.

So, since beginners today have much father to go then I did when I first started we try to encourage them to skip this sloppy "unstructured programming" step and jump right to structured programming so that they can get down to the business of being enlightened by modern techniques.

But you will still find that beginner programming is sloppy and unstructured (even with the use of control structures) and it takes a little while before order begins to creep in...

that is what avoiding goto is all about - bringing order and logical structure to your programming. The more orderly your programming the easier it is to abstract, the more abstract your programming the more you can do with the tools you develop.
Was This Post Helpful? 2
  • +
  • -

#8 Salem_c  Icon User is offline

  • void main'ers are DOOMED
  • member icon

Reputation: 1689
  • View blog
  • Posts: 3,209
  • Joined: 30-May 10

Re: Why is goto bad?

Posted 07 July 2011 - 06:58 AM

I'm thinking of a new paper called "Clinging to dogmatic absolutes considered harmful".

Like everything else in C (with the exception of gets()), there is a time and place for everything. Backward gotos are a sure sign you should be using one of the many loop constructs C offers. But careful and consistent use for say error trapping is not necessarily a bad thing either. Even the poster child for the structured programming movement couldn't quite commit to removing the goto statement.

Or you could go as far as MISRA-C by banning break and continue as well, since these are just semantic gotos without the need to define an explicit label.

Here's an example.
#include<stdio.h>

void foo ( ) {
  int i, j, flag = 0;
  for ( i = 0 ; i < 10 && !flag ; i++ ) {
    for ( j = 0 ; j < 10 && !flag ; j++ ) {
      if ( i*j == 42 ) flag = 1;
    }
  }
  printf("%d %d\n", i-1, j-1);  // flag not tested until after increment
}

void bar ( ) {
  int i, j;
  for ( i = 0 ; i < 10 ; i++ ) {
    for ( j = 0 ; j < 10 ; j++ ) {
      if ( i*j == 42 ) goto foundit;
    }
  }
foundit:
   printf("%d %d\n", i, j);
}

void baz ( ) {
  int i, j, flag = 0;
  for ( i = 0 ; i < 10 ; i++ ) {
    for ( j = 0 ; j < 10 ; j++ ) {
      if ( i*j == 42 ) flag = 1;
      if ( flag == 1 ) break;
    }
    if ( flag == 1 ) break;
  }
  printf("%d %d\n", i, j);
}

int main()
{
  foo();
  bar();
  baz();
  return 0;
}


Three functions, all doing the same thing, and all with a different kind of ugliness about them.

I suppose you could have
      if ( i*j == 42 ) {
        printf("%d %d\n", i, j);
        return;
      }


but that would just annoy the "single exit point" crowd.

In the end, it's choose your poison.
Was This Post Helpful? 3
  • +
  • -

#9 stackoverflow  Icon User is offline

  • D.I.C Addict
  • member icon

Reputation: 165
  • View blog
  • Posts: 545
  • Joined: 06-July 11

Re: Why is goto bad?

Posted 07 July 2011 - 07:36 AM

To be perfectly fair-- goto statements are not always bad. There are uses of them. In particular, escaping from deep nested blocks. To be more specific, escaping from deep nests into a clean up routine before completely exiting the function.

A little reading.. pretty much what I just said can be seen here with an example:

Quote

Albeit deprecated by some people, the equivalent of the goto statement is
used frequently by compilers in form of the unconditional jump instruction.

The goto statement comes in handy when a function exits from multiple
locations and some common work such as cleanup has to be done.

The rationale is:

- unconditional statements are easier to understand and follow
- nesting is reduced
- errors by not updating individual exit points when making
modifications are prevented
- saves the compiler work to optimize redundant code away ;)


int fun(int a)
{
	int result = 0;
	char *buffer = kmalloc(SIZE);

	if (buffer == NULL)
		return -ENOMEM;

	if (condition1) {
		while (loop1) {
			...
		}
		result = 1;
		goto out;
	}
	...
out:
	kfree(buffer);
	return result;
}


Was This Post Helpful? 1
  • +
  • -

#10 baavgai  Icon User is offline

  • Dreaming Coder
  • member icon

Reputation: 5848
  • View blog
  • Posts: 12,707
  • Joined: 16-October 07

Re: Why is goto bad?

Posted 07 July 2011 - 07:37 AM

View PostSalem_c, on 07 July 2011 - 09:58 AM, said:

as far as MISRA-C by banning break and continue as well


Um, the end of a loop block is also a goto... I wonder how they feel about return in a block? Alas, the document is the farthest thing from open source, so they may keep their wisdom in their ivory tower.

A lot of in house coding rules and standards impose limitations on code for one reason or another. I certainly don't know of any C coding standard that recommends goto. :P
Was This Post Helpful? 0
  • +
  • -

#11 stackoverflow  Icon User is offline

  • D.I.C Addict
  • member icon

Reputation: 165
  • View blog
  • Posts: 545
  • Joined: 06-July 11

Re: Why is goto bad?

Posted 07 July 2011 - 07:38 AM

View Postbaavgai, on 07 July 2011 - 02:37 PM, said:

View PostSalem_c, on 07 July 2011 - 09:58 AM, said:

as far as MISRA-C by banning break and continue as well


Um, the end of a loop block is also a goto... I wonder how they feel about return in a block? Alas, the document is the farthest thing from open source, so they may keep their wisdom in their ivory tower.

A lot of in house coding rules and standards impose limitations on code for one reason or another. I certainly don't know of any C coding standard that recommends goto. :P


See the post of mine above yours, :)
Was This Post Helpful? 0
  • +
  • -

#12 NickDMax  Icon User is offline

  • Can grep dead trees!
  • member icon

Reputation: 2250
  • View blog
  • Posts: 9,245
  • Joined: 18-February 07

Re: Why is goto bad?

Posted 07 July 2011 - 07:40 AM

I agree that this insistence upon avoiding certain techniques:

don't use goto!!!
don't use pointers!!!
don't use casts!!!
don't use system("puase")!!!
don't use conio.h!!!
don't use __________!!!

can be a little dogmatic and potentially harmful.

There are generally reasons for these "rules" but they are not absolutes. These are things that is is best to avoid but don't let avoiding them keep you from getting the job done.

The thing is that these are really not "rules" or "dogmatic absolutes" -- these are thumb rules -- things to avoid. They should read:

avoid using goto when structured programming can solve the problem more clearly and logically.
avoid using pointers if you can use references or smart-pointers or a container.
avoid using casts if you can try to maintain C++ type-safety
avoid using unnecessary costly platform dependent external system calls
avoid using depreciated libraries and functions
avoid using ___________ for whatever reasons there are to avoid ___________.

But there ARE times when using goto is just the ticket and maybe the only viable solution. For example avoiding the goto may require a costly refactoring. You can document why the goto is there and what need to be done to refactor this in the future but maybe there just is not time/money to refactor and test.

Point is -- these are good advice but not absolutes. you CAN use goto and not have your computer blow up and lava seep from your hard drive. Using goto does not cause droughts in Africa or war in the middle east.

You will find that learning to avoid these things is part of growing as a programmer but you need to know WHY they are to be avoided and sometimes that takes burning your figures a little and learning a lesson now and again.
Was This Post Helpful? 2
  • +
  • -

#13 baavgai  Icon User is offline

  • Dreaming Coder
  • member icon

Reputation: 5848
  • View blog
  • Posts: 12,707
  • Joined: 16-October 07

Re: Why is goto bad?

Posted 07 July 2011 - 07:40 AM

View Poststackoverflow, on 07 July 2011 - 10:36 AM, said:

goto statements are not always bad


Always bad... :P
int fun(int a) {
	int result = 0;
	char *buffer = kmalloc(SIZE);

	if (buffer == NULL) {
		result = -ENOMEM;
	} else {
		if (condition1) {
			while (loop1) { /* ... */ }
			result = 1;
		} else if (condition2) {
			/* ... */ 
		}
		kfree(buffer);
	}
	return result;
}


Was This Post Helpful? 1
  • +
  • -

#14 PlasticineGuy  Icon User is offline

  • mov dword[esp+eax],0
  • member icon

Reputation: 281
  • View blog
  • Posts: 1,436
  • Joined: 03-January 10

Re: Why is goto bad?

Posted 07 July 2011 - 07:42 AM

why spaghetti code spawned from goto is bad
Was This Post Helpful? 0
  • +
  • -

#15 stackoverflow  Icon User is offline

  • D.I.C Addict
  • member icon

Reputation: 165
  • View blog
  • Posts: 545
  • Joined: 06-July 11

Re: Why is goto bad?

Posted 07 July 2011 - 07:44 AM

That wouldn't work without a lot of extra conditionals and re-writing of code used elsewhere, and the nesting would get too deep violating the 80 character per-line guideline. The Linux kernel uses the goto method for those kinds of situations.

:)
Was This Post Helpful? 0
  • +
  • -

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