A little... extension for C++

Posted on January 24, 2011 by phimuemue

Loops are used on a daily base by almost every programmer. Especially for-loops occur quite often.

Now, have you ever felt it's quite cumbersome to code something like the following:

for (int i=0; i<10; ++i){
  do_something_here();
}

while you just wanted to write

10 times {
  do_something_here();
}

and wanted C++ to understand it?

Don't worry, here's the solution.

Just include this little header file and everything will work fine.

This stuff should be valid standard ISO-C++. I tried it using g++ v.4.3, 4.4 and 4.5 on Ubuntu 10.04, but it shouldn't be problematic to use with other compilers on other operating systems.

Advanced usage

Of course it would be handy to have acces to the current counter. This is possible via a counting variable named _ (just a single underscore):

#include <stdio.h>
#include "extend.h"

int main(int argc, char *argv[]) {
  int a=3;
  --a*2 times {
    printf ("outer: %d\n", _);
    _ times {
      printf ("inner: %d\n", _);
    }
  }
  return 0;
}

The above example will produce the following output:

outer: 0
outer: 1
inner: 0
outer: 2
inner: 0
inner: 1
outer: 3
inner: 0
inner: 1
inner: 2

You see, the construct is also able to deal with nested loops.

So how does it work?

It's quite simple. The header file defines a new class, that has an overloaded operator operating on a preceding integer. This class has a static variable, which is set via the operator call.

Now, I defined a preprocessor macro converting times to a call to the operator and generating a foor loop using two variables. One is the actual counter variable counting down (it's named __), the other is a variable that can be used just like any ordinary simple-for-loop-variable (called _).

How can I get it?

Just put the following code somewhere before you want to use it:

#ifndef C_MOST_USEFUL_EXTENSION_EVER
#define C_MOST_USEFUL_EXTENSION_EVER
class _t{
public:
  static int _count;
  _t(){};
  virtual ~_t(){};
  friend const void operator+(const int n, const _t t){_count=n;}
};
int _t::_count=0;
_t ____t;
#define times   +____t; for (unsigned int __=_t::_count, _=0; __>=1;
--__,++_)
#endif