using macro with preprocessor directive #define I have written the following two codes.
_valid_pagesize(a+b)
c=a+b
and then passed this c as an argument to macro.
_valid_pagesize(c)
the second code runs perfectly whereas the first code doesn't. can we not pass expressions as arguments to macro like the way we can in case of a function..? why not..?
the code passing expression as argument :
#include<stdio.h>
#include<stdlib.h>
#define _valid_pagesize(_newsize) (!(_newsize % 0x80000000)?1: \
(!(_newsize % 0x40000000)?1: \
(!(_newsize % 0x10000000)?1: \
(!(_newsize % 0x4000000) ?1:0))))
int main(int argc, char* argv[]){
uint64_t size[2];
size[0]=atoi(argv[1]);
size[1]=atoi(argv[2]);
if(_valid_pagesize(size[0]+size[1])){
printf("success\n");
}
return 0;
}
Rule #1 with macros is to enclose all arguments in parentheses, to avoid exactly the problem that you're seeing.
#define _valid_pagesize(_newsize) (!((_newsize) % 0x80000000)?1: \
(!((_newsize) % 0x40000000)?1: \
(!((_newsize) % 0x10000000)?1: \
(!((_newsize) % 0x4000000) ?1:0))))
When you pass a+b
to the macro, it expands to
a + b % 0x40000000
and since %
has higher precedence than +
, you don't get the result you expect. By enclosing the argument in parentheses, the macro expands to
(a + b) % 0x40000000
which works as expected.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments