user5622060
user5622060

Reputation: 69

C++ ## macro doesn't work

A macro with a ## will concatenate the two elements together, for example if you use #define sptember oct ## ober you will obtain october.

So my problem is: I have a macro like this #define getRegByPin(pin) set ## pin than I have from 1 to 19 some defines like this: #define set0 xxx and #define set1 xxx, etc.

But when I call my macro in code int p = getPinNo(pin); st(getRegByPin(p), p, to); it replaces getRegByPin(p) with setp instead of set0 or set13 or etc.

What can i do?

Thx for help! You are awesome! :)

Upvotes: 0

Views: 306

Answers (1)

The C preprocessor (and C++ has just inherited it), just does textual substitution. It knows nothing of variables. So given

#define getRegByPin(pin) set ## pin
const int p = 5;

getRegByPin(p);  // Will expand to setp, not set5

From the syntax, I guess that set0 to set13 are constants. Do they have values you can calculate? For example:

auto getRegByPin(int pin) { return set0+pin; }  // or (set0 << pin)

If not, you are going to need a constant array which you can index:

auto getRegByPin(int pin) {
    static const setType_t pins[16] = { set0, set1, set2 ... set15};
    return pins[pin];
}

If they are not constants, but functions, your array will need to be an array of function pointers.

Prefer to use functions than the preprocessor.

Upvotes: 1

Related Questions