The shortcomings of C: (v) control structures

Firstly, C allows the goto statement. This is not as terrible as out once was, because most people tend to ignore it. The switch statement is somewhat primitive when one considers better forms of the case statement. The main issue is that lack of ability to put ranges of numbers, and the use of break when follow-through is not required. Allowing ranges would have likely circumvented the need for break. It is annoying to have to write break after each case that isn’t a fall -through. It would be much easier to have the break implicitly implied, and instead apply a fall through explicitly using a term like fallthrough (as in Swift). The switch statement is in reality nothing more than syntactic sugar for an if-else-if chain. Consider the following piece of code (from Stupid Switch (II) – Bad Design).

   switch(x) {
      int i = 4;
      case 0:
         j = i * i;
      default:
         printf("%d %d\n", i, j);
   }

The output when this is run is: 3 9, which is weird considering I is set to 4. The problem is that this is done inside the switch statement, something that shouldn’t really be allowed, but it is. The problem is that while the variable is declared, it is not initialized, and therefore contain indeterminate values. On another system (Linux), the output is 32766 1073610756. But the compiler does allow it, although pushes a warning that the “statement will never be executed”. Consider another case:

   switch(x) {
      case 0:
         int i; i = 2; printf("%d", i);
         break;
      case 1:
         x++; break;
   }

This will force an error of the form: “a label can only be part of a statement and a declaration is not a statement“. However enclosing the statements in { }, allows the program to compile.

   switch(x) {
      case 0:
         {int i; i = 2; printf("%d", i);}
         break;
      case 1:
         x++; printf("%d", x); break;
   }
   return 0;

If x=0, the resulting value of i is still indeterminate (when I ran it I got “2%”).

The for statement is also somewhat obtuse, and powerful. It is easy to incur a side-effect, or change the value of the iterated variable, or use the comma operator to abbreviate the code even further. It would be easier if C, like Swift offered the ability to iterate over the items in an array, or have a for-in loop for numeric ranges. When a for loop is used in conjunction with an array, there is no testing for array bounds validity.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.