简体   繁体   中英

How do you include parentheses in a #define statement in C

Assume I have a function C.

uint8_t readPin(uint8_t);

uint8_t readPin(uint8_t pin_num)
{
    switch pin_num
    {
        case 0:
            return(PORTAbits.RA3);
            break;
        case 1:
        ...and so on
    }
}

I want to call the pin using a more human readable name (that can be remapped). For example, I want to be able to write:

openDoor();

to call

readPin(2);

I tried using

#define openDoor() readPin(2)

but that doesn't work because of the parentheses. Does anyone have a suggestion on how best to do this? I can't just rename the readPin function because I want to have more than 1 different aliases for it depending on which header file I include.

#define openDoor() readPin(2)

What you have is fine. Macros can have argument lists, even empty argument lists, so this will do what you want.

However, I caution against using the preprocessor like this. It's best to avoid using the preprocessor, particularly when the language can do the exact same thing. Debuggers can't see preprocessor macros, for one thing.

void openDoor()
{
    readPin(2);
}

#define openDoor() readPin(2)

It should work fine. Because , #define is used just to replace wherever it finds the replacing token with the appropriate value defined for it before compiling that is preprocessing.

So, if you write openDoor() it will replace with readPin(2) before compilation

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