Web for Nerds !!!

goto statements

Many a times I came across fellow engineers specially who look and behave like geeks ask me how do I write code in C, which need to jump from middle of nested if blocks.

As far as I remember, I never thought about nested-if-jump was an issue (???) until I met the first person who asked *this* tricky IQ question (believed to be) during a weekend beer party, funnily after couple of rounds of dark beers. In semi-intoxicate state, it took me while to understand what he was asking. I think, I answered him several possibilities. Lately, I understood, he is one who will never agree upon others answer, I decided to quit.

Few months later, second person who just got introduced by my colleague also told him that I’m a “good” programmer. New friend took no time to ask me the same question, how do we jump from nested if block? I smiled at him and said “I don’t know”, he seemed not convinced that I’m not interested in answering his question, he insisted repeatedly, also hinting me “far jump”, “long jump” etc. Few people have some points prove, I quit for second time saying that “I really don’t know the answer”.

It’s not that, I did not understand importance of using and NOT using goto. Even before the first person, I found several snippets of code in large project sources, goto were common. Reading several device driver code, I made a note that it’s not easy to escape “goto” without rewriting entire block of code plus keeping the interfaces which are already defined. I rewrote some blocks, but I was not really happy, I achieved too less in performance, but lost some readability or natural code flow.

After second person, there were few more instances like that, I’m happy that those were not like first two. My definitive answers were
(1) Design your code well, so that we do not get into multiple or deep if nesting.
(2) In a good design, if it becomes necessary to use goto, use it, there is no harm.

There were some level of debate on portability issues, readability or scalability etc.. which I always felt from theoretical and not practical.

Years later, when google become powerful search engine, I found an article from Prof. Don Knuth, who wrote a white paper, covering every details, cross references with other languages and complete history and analysis, I can call it a master piece of “goto” statement. Prof. Knuth’s white paper is more than 35 years old, but still stand fresh and undisputed.

I recommend Prof. Donald E. Knuth’s white paper titled “Structured Programming with goto statement” for further reading.

Search Google PDF here
Leave a Reply

You must be logged in to post a comment.