0

Not sure how to word this but, Is there any way to increment a macro?

I have several offset macros, the first defined offset must be zero, the next one must be 1, and so on. If I need to add an offset macro to the middle of the list, it can be cumbersome to increment all the offsets below it manually.

//How can I turn this... // v This number needs to increment by 1 (no matter the order) #define OFFSET_X 0 #define OFFSET_Y 1 #define OFFSET_Z 2 #define OFFSET_W 3 //Into something like this... (order of macros swapped yet the numbering still goes from 0 to 3) int num = 0; #define OFFSET_Z num++ // = 0 (was 2) #define OFFSET_Y num++ // = 1 (was 1) #define OFFSET_X num++ // = 2 (was 0) #define OFFSET_W num++ // = 3 (was 3) 
17
  • 7
    Use an enum instead? Commented Jun 2, 2018 at 21:51
  • 1
    __COUNTER__ is not standard afaik. Commented Jun 2, 2018 at 21:53
  • 4
    The best dreams I have are those of the death of macros. Commented Jun 2, 2018 at 21:55
  • 4
    Looks like you’re reinventing enums. Commented Jun 2, 2018 at 21:59
  • 2
    There is no overhead to it. Its identical performancewise. (enums are compiletime constants) Commented Jun 2, 2018 at 22:07

2 Answers 2

1

With the original order,

#define OFFSET_X 0 #define OFFSET_Y (OFFSET_X + 1) #define OFFSET_Z (OFFSET_Y + 1) #define OFFSET_W (OFFSET_Z + 1) 

or with the revised order in the second part of your post,

#define OFFSET_Z 0 #define OFFSET_Y (OFFSET_Z + 1) #define OFFSET_X (OFFSET_Y + 1) #define OFFSET_W (OFFSET_X + 1) 

etc. Since all this gets evaluated at compile time, anyway, there's no perf hit.

Or you could write a code generator, if you're really bored, and have it generate the values for you.

Or just use an enum. This is what they're for, and they're treated as constants by the compiler, anyway - but you get compile-time error checking which is far less effective with macros.

BUT, a better solution may be constexpr added in C++11.

In any case, if you only have four of these, this is overkill.

Sign up to request clarification or add additional context in comments.

Comments

0

Just use an enum:

enum class offsets { X = 0, Y = 1, Z = 2, W = 3 }; 

and don't sweat it. Want auto-increments? Even easier:

enum class offsets { X = 0, y, z, w }; 

for the same effect.

Note I've suggested an enum class, so the usage is offsets::X, offsets::Y etc.

In some cases you may prefer an constexpr std::array, which you could then iterate over (something you can't do with macros or enums).

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.