Software, technology, sysadmin war stories, and more. Feed
Friday, September 28, 2012

Follow the flow of this code if you can

Yesterday, I wrote about the so-called "magic GOTO". Read that post if you haven't seen it yet, since you will be tainted once you read this one. Go on. I'll wait.


I posted that yesterday because I wanted to give everyone a chance to think about the flow within code and determine what they think is normal. I imagine there will be a bunch of different positions on this, and some people can handle things going every which way, and others don't like it at all.

While we're still thinking about following code, let's analyze this. Do you know what it will print? Assume it's compiled with g++ with no funny flags (no -f magic). See if you can follow it entirely by sight and without compiling it.

#include <stdio.h>
static void f4() {
  printf("f4 running\n"); 
  throw "ouch";
  printf("f4 done\n");
static void f3() {
  printf("f3 running\n"); 
  printf("f3 done\n");
static void f2() {
  printf("f2 running\n"); 
  printf("f2 done\n");
static void f1() {
  printf("f1 running\n"); 
  try {
  } catch (...) {
    printf("f1 caught an exception\n");
  printf("f1 done\n");
int main() {
  printf("main starting\n");
  printf("main done\n");
  return 0;

Now go compile it and run it. Were you right?

I can't claim to have arrived at this feeling about exceptions by myself. I had certain things beaten into me by the corporate C++ style guide between 2006 and 2011. In particular, check out these specific parts: exceptions and doing work in constructors.

By virtue of my former access to the code depot, I got to see mountains of code (usually) written according to that guide, and the collective output from that depot did lots of work. It made things run at scales the likes of which I had never seen before.

If your metric is what you can do with something, it's hard to argue with that.