The following construct compiles in VisualStudio 2013. I just made a new consoleApplication project and only changed the main .cpp, so you can just paste this and try it out. What it apparently does is create an end-recursive variadic macro.
#include "stdafx.h"
#include <iostream>
using namespace std;
#define DEFINE_ENUM_VALUE(name, i) name = i,
#define _DEFINE_ENUM_VALUES(i, name, ...) DEFINE_ENUM_VALUE(name, i+1)
#define DEFINE_ENUM_VALUES(enum_name, name, ...) enum class enum_name{ \
DEFINE_ENUM_VALUE(name, 0) _DEFINE_ENUM_VALUES(1, __VA_ARGS__) \
};
DEFINE_ENUM_VALUES(names, _0, _1, _2, _3, _4, _5, _6, _7, _8, _9)
int _tmain(int argc, _TCHAR* argv[])
{
cout << (int)names::_0 << ' ';
cout << (int)names::_1 << ' ';
cout << (int)names::_2 << ' ';
cout << (int)names::_3 << ' ';
cout << (int)names::_4 << ' ';
cout << (int)names::_5 << ' ';
cout << (int)names::_6 << ' ';
cout << (int)names::_7 << ' ';
cout << (int)names::_8 << ' ';
cout << (int)names::_9 << ' ';
return 0;
}
This not only compiles, but also works only nearly as one may imagine. The output is this:
0 1 2 3 4 5 6 7 8 2
This is not a typo, the value of names::_9
is 2. And this is the case for every enum defined like this, the last value is always 2. I tested this with a whole range from 3-15 arguments.
Does anyone have an idea what's going on here?
Why is the MSVC pre-processor expanding DEFINE_ENUM_VALUE
multiple times? And why, if it's intended behaviour (which I doubt), does it make the last value 2?
I also tested it with ideone, and it did fail to compile as expected, noting that everything after names::_1
wasn't part of names
.