简体   繁体   中英

C Macro Expression Return Value

I am writing a devices handler for my embedded systems class and I am trying to use a macro to check if the ith bit is set. My macro doesn't seem to work correctly but the inline function does. Why is that?

#define TEST0 i&0x01
#define CLEAR0 i &= 0x01


inline short test0(short i) {
    return i&0x01;
}


int main() {
    short flag = 1;

    //this doesnt work
    if (TEST0(flag) == 0x01) {
        CLEAR0(flag);
    }

    //but this does
    if (test0(flag) == 0x01) {
        CLEAR0(flag);
    }

    return 0;
}

Syntax error. The macro needs an argument.

#define TEST0(i) ((i) & 0x01)

Also, use whitespace for readability and parentheses for security.

It's due to operator precedence problems. Also, you need a parameter to your macro.

It's being parsed like this:

if (i & (0x01 == 0x01))

Add parens and a parameter to fix:

#define TEST0(i) ((i)&0x01)
#define CLEAR0(i) ((i) &= 0x01)

If you want to pass an argument to your macro, it should be defined to accept an argument:

#define TEST0(i) ((i)&0x01)
#define CLEAR0(i) do { i&=0x01; } while(0)

(other modifications deal with precedence and syntax).

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