TITLE: no go (to) (Newsgroups: comp.lang.c++, 26 Sept 97) ROBERTSON: Evin C Robertson > Why are some people opposed to using the goto statement? Most of the > people I have read say everything has its place, even macro functions > and gotos. KOENIG: ark@research.att.com (Andrew Koenig) On the off-chance that this article is not a troll, I suggest you go to the library and read Don Knuth's article ``Structured Programming with goto Statements'' which appeared, I think, in the January 1971 issue of Computing Surveys. Then come back and we'll talk. He has more to say, and says it better, than I ever could. ROBERTSON: > Take the following snippet of code: > void sort(unsigned a[50], unsigned b[50], unsigned *same, unsigned *different) > { > for(unsigned aindex = 0; aindex < 50; aindex++) > { > for(unsigned bindex = 0; bindex < 50; bindex++) > { > if(a[aindex] == b[bindex]) > { > *same++ = a[aindex]; > goto done_searchb; > } > } > *different++ = a[aindex]; > done_searchb: > } > } > This could be done without the use of the goto, but it becomes messier, > less efficient (slower and bigger), and less readable: KOENIG: That depends on how one rewrites it: void sort(unsigned a[50], unsigned b[50], unsigned *same, unsigned *different) { for (unsigned aindex = 0; aindex < 50; aindex++) { unsigned bindex = 0; while (bindex < 50 && a[aindex] != b[bindex]) ++bindex; if (bindex < 50) *same++ = a[aindex]; else *different++ = a[aindex]; } } Even better might be to use an algorithm from the standard library: void sort(unsigned a[50], unsigned b[50], unsigned *same, unsigned *different) { for (unsigned aindex = 0; aindex < 50; aindex++) { if (find(b, b+50, a[aindex]) != b+50) *same++ = a[aindex]; else *different++ = a[aindex]; } } ROBERTSON: > I'm sure there are better examples of good goto use, but I give you this > because searching through arrays like this is very common. KOENIG: Indeed. That is why there are standard library algorithms to search through arrays. And even if you don't use them, goto statements are far from the cleanest way to express such algorithms.