Monday, March 23, 2009

About break statements

In a recent article, Andrew Koenig argues that break statements are harmful because they make it harder to deduce the program context at loop termination. For instance, given:

while (n != 0) { /* do something */ }
n can be assumed to be zero at loop termination unless there is a break within it. Koenig proposes two different approaches to alleviating this problem:

  • Include the program context at the break statement as a possible value for the program context at loop termination.
  • Force the loop termination condition just before breaking.

There is another alternative: exclude the loop termination condition from the evaluable program context. Here is a way to do that:

for (int local_n = n; local_n != 0;) { /* do something with local_n */ }
As the scope of local_n does not extend outside the loop, program context after loop termination does not depend on the termination procedure. A cruder, but also more flexible way to do the same is the following:
‎ int local_n = n;
‎ while (local_n != 0) { /* do something with local_n */ }
The somewhat unexpected surrounding braces are a conspicuous reminder that local_n does not form part of the global program state.

1 comment :