Reputation: 37
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;
}
Upvotes: 1
Views: 2507
Reputation: 21507
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).
Upvotes: 0
Reputation:
Syntax error. The macro needs an argument.
#define TEST0(i) ((i) & 0x01)
Also, use whitespace for readability and parentheses for security.
Upvotes: 3
Reputation: 53027
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)
Upvotes: 1