Thought Leadership

Take a break – the break statement in C

By Colin Walls

It is a given that structured programming – in one form or another – is a Good Thing. For years, the spaghetti of GOTOs that arose in earlier programming languages has been abhorred by all right-thinking programmers. There are good reasons for this attitude. Firstly, structured code tends to be easier to debug and, second, the code is more readable and, hence, maintainable. Both of these are productivity improvements, so the GOTO should clearly be avoided.

But, what about the break statement in C? …

The break statement has two, closely related uses in C: it enables each “clause” of a switch statement to be exited neatly; it enables premature exit from loop/logic constructs.

In a switch statement, it is hard to imagine a sensible alternative in most cases. This code, for example:

switch (ss)
{
case 1:
   alpha();
   break;
case 5:
   beta();
   break;
case 11:
   gamma();
   break;
default:
   panic();
   break;
};

is quite clear. Though I guess some might argue that the last break is redundant. It actually makes the code more maintainable and has no effect on the resulting executable, so I feel that it should stay.

In a complex loop – or even quite a simple one – there may be a need for premature exit. This can be done by a “kluge” – messing with the loop counter/conditions, for example – but that is unwise. Or a “structured” exit process may be included, thus:

for (i=0, exitflag=FALSE; i<100 && !exit_flag; i++)
{
   retcode = myfunction();
   if (retcode == -1)
      exitflag=TRUE;
}

However, I feel that this is much easier to follow:

for (i=0; i<100; i++)
{
   retcode = myfunction();
   if (retcode == -1)
      break;
}

If you have a view, please get in touch by email or comment or via social media. I have my tin helmet at the ready.

Comments

0 thoughts about “Take a break – the break statement in C
  • Mr. Colin:

    When you say there may be a need for premature exit from a loop; or any part of the logic structure for that matter, I tend to cringe at the thought of a departure without adequate consideration of all the variable states that were in play during execution. At the very least, there may be a need to report the various values of certain key variables that were critical just prior to abort.

    Luis Freire
    Rutgers University

Leave a Reply

This article first appeared on the Siemens Digital Industries Software blog at https://blogs.sw.siemens.com/embedded-software/2016/08/22/take-a-break-the-break-statement-in-c/