computer science goes bonk / all posts / rss / about

if, switch, and RAII

I ran into some C++ code yesterday that made me wince. It looked something like this snippit (code obfuscated to protect the guilty innocent):

int result = -1;
switch (foo) {
  case FOO_VALUE_A:
    int i = foo();
    result = baz(i);
  case FOO_VALUE_B:
    int j = qux();
    result = quxx(j);
  // (and so on)

In order to declare new variables inside a case of a switch, we need to use curly braces to establish some scope for those variables to hang out in. But (is your spidey sense tingling yet?) in this example, those little scopes might almost make you overlook the fact that the switch is completely devoid of any breaks or returns, which means we'll execute multiple cases serially. That's probably not desired behavior.

This is why I hate switch as a language construct.

One way to think of it is like this: switches have the same problem that raw pointers have. A raw pointer needs to be manually deleted at some point after it has been allocated. If you forget to perform this final action, the memory will leak from a localized region of time to future regions of time:

void foo() {
  Bar *b = new Bar();
  // ...
  delete b;

A std::unique_ptr, on the other hand, ties the deletion of that memory to a specific scope, ensuring that you won't leave that scope without deallocating your resource:

void foo() {
  std::unique_ptr<Bar> b(new Bar());
  // ...
}    // b goes out of scope, memory automatically deleted

Now, instead of thinking of memory leaking from one interval of time to another, think of control flow leaking from one area of code to another.

Using if helps ensure that your control flow won't leak from one condition to another. You don't need to worry about "deallocating" the condition when you reach the end of it. But if you forget to break after every case, you'll leak. You'll leak control.

Sure, switch can be used responsibly. So can raw pointers. If your last name is Kernighan or Ritchie, go nuts. Throw in some gotos, while you're at it. For most people, however, switch is a bad construct.