Open side-bar Menu
 Embedded Software
Colin Walls
Colin Walls
Colin Walls has over thirty years experience in the electronics industry, largely dedicated to embedded software. A frequent presenter at conferences and seminars and author of numerous technical articles and two books on embedded software, Colin is an embedded software technologist with Mentor … More »

Take a break – the break statement in

 
March 16th, 2021 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;
}

Logged in as . Log out »




© 2024 Internet Business Systems, Inc.
670 Aberdeen Way, Milpitas, CA 95035
+1 (408) 882-6554 — Contact Us, or visit our other sites:
TechJobsCafe - Technical Jobs and Resumes EDACafe - Electronic Design Automation GISCafe - Geographical Information Services  MCADCafe - Mechanical Design and Engineering ShareCG - Share Computer Graphic (CG) Animation, 3D Art and 3D Models
  Privacy PolicyAdvertise