Alex Rivera | Logout

How to use goto to break a nested loop

Asked 2012-09-27T00:44:03.990
8

How can I use a "goto" statement to break out of a loop

for(i = 0; (i < 9); i++)
    {
        for(j = 0; j < 9; j++)
        {
            //cout << " " << Matrix[i][j];
            //cout << "i: " << i << endl;
            if(Matrix[i][j] == 0)
            {
                //temp = 10;
                [goto] ;
                //break;
            }
        }
    }

I wanted to keep the values at which i and j were when I left the nested for loop. How can I use a goto statement for that?

Edit
Report

1 Answer

2

Well, @bitmask's answer has already said most of what I thought of saying when I read the question.

But for completeness, here's another technique:

Matrix              m;
Index2D< 9, 9 >     pos;

for( ; pos < pos.end();  ++pos )
{
    if( m( pos.x(), pos.y() ) == 0 )
    {
        break;
    }
}
cout << pos.x() << " " << pos.y() << endl;

IMHO this is far more clear code.

Also, the matrix can then be made to support indexing via Index2D values, thus reducing the above to just …

Matrix              m;
Index2D< 9, 9 >     pos;

for( ; pos < pos.end();  ++pos )
{
    if( m[pos] == 0 )
    {
        break;
    }
}
cout << pos.x() << " " << pos.y() << endl;

Since there’s nothing like Index2D in the standard library, it needs to be defined somewhere, e.g. like

template< int width, int height >
struct Index2D
{
    int         i_;

    int x() const { return i_ % width; }
    int y() const { return i_ / width; }

    void operator++() { ++i_; }

    bool operator<( Index2D const& other ) const
    {
        return (i_ < other.i_);
    }

    Index2D(): i_( 0 ) {}

    Index2D( int const x, int const y )
        : i_( width*y + x )
    {}

    static const Index2D endValue;
    static Index2D end() { return endValue; }
};

template< int width, int height >
Index2D< width, height > const Index2D< width, height >::endValue( 0, height );

But then it can be reused everywhere that you need this functionality.

answered 2012-09-27T02:06:54.743

Your Answer