Re: Can throw-catch be used as substitute for goto?
artella.coding@googlemail.com wrote:
try{
for(int row = 0; row < asize; ++row){
for(int col = 0; col < asize; ++col){
cout<<"row = "<<row<<", col = "<<col<<endl;
if(row==2 && col==2){
throw escape;
}
}
}
}catch(int){}
Just a few comments on this:
1. I guess that this is e.g. some search in a 2D array. In that case, a
simple 'goto' with a well-chosen target label name is a very clear way to
express the intention. Yes, it is frowned upon, but it may actually be much
clearer.
2. You could avoid this by e.g. using an iterator:
for( rc_iterator it(0,0,asize), end(asize,asize,asize);
it!=end;
++it) {
...
if(it.x==2 && it.y==2)
break;
}
Writing an iterator might seem a lot of work for such a simple task, but
using e.g. Boost's iterator construction library it is rather easy and it
sometimes makes it easier to concentrate on the relevant parts instead of
the framework like getting loops right.
3. You could also put the code following the 'goto' label into the center of
the loop and then return, or put the search-algo into its own function
returning the element in question or NULL.
Uli
--
Sator Laser GmbH
Gesch?ftsf?hrer: Ronald Boers, Amtsgericht Hamburg HR B62 932
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]