Magic

Projects (especially, B.Tech Projects) are very fascinating, in that they let you do a lot of things just for the sake of it. For example, at one point in my code, I wanted to iterate through all the 4-element subsets of a given N-element set. The most straightforward way would be to actually write 4 nested loops. A bit “scalable” approach would probably employ proper recursion.

Or.. we could do some goto magic!

int i[4];
int m=0;
 nest:
for(i[m]=(m?i[m-1]+1:0);i[m]<10;i[m]++){
    if(m<3) {m++; goto nest;}

    cout<<i[0]<<i[1]<<i[2]<<i[3]<<endl;

  unnest:
    ;
  }
  if(m>0) {m--;  goto unnest;}

The above C++ code will iterate through (and print) all 4-subsets of {0,1,..,9}.

How does it work? To understand that, one needs to appreciate a very simplistic view of compilation, namely that it is just a highly complex regexp find-replace operation. (Of course, this is oversimplifying things; since so many intermediate steps and much optimization happens; but we’ll ignore that, because all that does not define (or change) the external behavior of the program)

In other words, processors have no real sense of understanding about what the program syntax means. Code is just executed as it comes along; and the code can be doing absolutely anything. And this is precisely what the above snippet makes use of. The nest and goto-nest is a small nesting loop that blindly steps our program flow 4 levels deep into for-loops. The processor has simply no idea that it is seeing the same for-statement again and again! It simply executes it, which is to say it nests up another level each time.

And then, the unnest-loop is needed to formally exit all the nested levels, so that the program can continue execution ahead. Again, the processor is given the illusion that it is encountering four quite distinct ‘unnesting’ operations.

Word of caution: goto is considered hazardous, and the above snippet indicates why: simply because then the program flow takes strange routes, difficult to keep track of. But the above also suggests that if somehow you can manage the ‘proofreading’, goto can do some beautiful things for you.

Advertisements

5 responses to “Magic

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s