Wednesday, August 18, 2010

Breaking a Loop with ``goto''

Consider the following code, which matches a vector u to another vector v and then executes some functions if u == v

bool equal = true;
for(int i=0; i<n; i++)
   if(u[i] != v[i]){
      equal = false;
      break;
   }
if(equal){
   /* do something with u and v */
}

Compared to the equivalent one using goto

for(int i=0; i<n; i++)
   if(u[i] != v[i])
      goto _inequal;
/* do something with u and v */
_inequal: ;

In such situation, using goto makes the code shorter and more intuitive.

No comments: