0

Possible Duplicate:
GOTO still considered harmful?

When is it acceptable to use GOTOs?

For example, is this code an acceptable use of GOTO? Why or why not?

        for (int y = 0; y < largest.Rectangle.Height; y++) {
            //the line is a goodie
            if (whitePixelCountPerLine[y] > threshold) {
                //g.DrawLine(new System.Drawing.Pen(Color.Blue, 1), largest.Rectangle.X, largest.Rectangle.Y + y, largest.Rectangle.X + largest.Rectangle.Width, largest.Rectangle.Y + y);
            } else {
                whitePixelCountPerLine[y] = 0;
                //check above it
                for (int i = y; i > 0 && i > y - distanceThreshold; i--) {
                    if (whitePixelCountPerLine[i] > threshold) {
                        //g.DrawLine(new System.Drawing.Pen(Color.Blue, 1), largest.Rectangle.X, largest.Rectangle.Y + y, largest.Rectangle.X + largest.Rectangle.Width, largest.Rectangle.Y + y);
                        whitePixelCountPerLine[y] = 1;
                        goto Endloop;   //if I break here, we still do the second loop, so a goto is the most readable way to skip
                    }
                }
                //check below it
                for (int i = y; i < largest.Rectangle.Height && i < y + distanceThreshold; i++) {
                    if (whitePixelCountPerLine[i] > threshold) {
                        //g.DrawLine(new System.Drawing.Pen(Color.Blue, 1), largest.Rectangle.X, largest.Rectangle.Y + y, largest.Rectangle.X + largest.Rectangle.Width, largest.Rectangle.Y + y);
                        whitePixelCountPerLine[y] = 1;
                        goto Endloop;   //keeping with the pattern
                    }
                }
            }
        Endloop:    //AH! A label for a GOTO, see the two goto statements above, they say why this is needed.
            continue;
        }
Community
  • 1
  • 1
Malfist
  • 30,221
  • 60
  • 180
  • 266
  • 3
    That is a unacceptable piece of code IMO. – Otávio Décio Jan 31 '11 at 15:34
  • 1
    Point taken, however, given the code sample, and the fact that it was in C, it doesn't need the goto, and can be re-actored to be cleaner without it. I have personally never encountered code where the use of a goto clarified the code. That I think about it I've seen routines (in the .net System.IO namespace actually) that - for speed - use goto (obviously I didn't write them, and boy are they ugly). I'll delete my answer, I still don't plan on using goto, but to be honest with myself, if it's the only tool that fits the job I'd use it. I stand down from my dogmatic **Never**. – Binary Worrier Jan 31 '11 at 17:31

0 Answers0