C/C++ Preprocessor Metaprogramming - Applications: Variable Dumping

Another small thing I found this useful for was outputting multiple variables for debugging purposes. I wanted to output variables and their respective values in one call. We can use FOR_EACH to help us achieve this.

#define STRINGIFY(x) #x
#define DUMP_VAR(x) std::cout << STRINGIFY(x) << ": " << x << std::endl;
#define DUMP_VARS(...) \
  std::cout << __FILE__ << " (Line #" __LINE__ << ")" << std::endl; \
  FOR_EACH(DUMP_VAR, __VA_ARGS__)

int main()
{
  int a = 10;
  string b ("Foo");
  float c = 1.4f;

  DUMP_VARS(a, b, c);
  /*
    Foo.cpp (Line #11)
    a: 10;
    b: Foo;
    c: 1.4f;
  */
}