简体   繁体   中英

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); 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! :)

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM