Adi Drumea

Thursday, June 02, 2005

[C/C++] Mind the implicit goto

Those of you with a higher degree of education probably heard at least one teacher saying goto is evil. While this is constantly argued by people all over the world, goto will continue to have its group of fans (me included). Dijkstra was against it (http://www.acm.org/classics/oct95/), while Torvalds kind of likes it (http://kerneltrap.org/node/553). A few days ago, I was modifying a horrible piece of software written in C++/MFC with lots of switch(...) statements. At some point, I needed to exclude some of the cases of the switch based on another condition. So, without thinking (this is what I usually do when modifying garbage - I don't think, I just write hoping it works), I wrapped some of the case statements in an if statement, like:

switch (x)
{
case 0: ...; break;
case 1: ...; break;
if (condition)
{
case 2: ...; break;
case 3: ...; break;
}
}

At the moment I wrote this and it compiled, I assumed I was doing the right thing. But, as I recently discovered, I didn't: the condition never evaluates because it's simply jumped over by the switch statement. At first I was outraged by this and that the compiler didn't warn me about anything. But then I thought a bit more, I tested with Vc++ 6 and gcc which exhibit the same silent behaviour, I looked over the C++ grammar, and realized I was wrong. The 'case' is just another label, and as you can use goto to jump into/out of various contexts, it should have the same behaviour regarding jumping into the middle of contexts. And it has. So, avoid writing crap as above: it may look ok to you, but it deffinitely does not do what one (uneducated individual) would expect.

1 Comments:

  • thought-provoking, mootable pv. just my thoughts, well anyways gl & be chipper is what i say

    By Anonymous Anonymous, at 5:47 PM  

Post a Comment

<< Home