Benefits of using Macro
What is the Macro? If you write as “#define” in your code, that is “Macro” .
Macro will handle by the preprocessor. You can think Macro as a method to replace the String which appears in you code..
pros: – run faster than writing as function
cons: – occupy memories
concepts: – there is no the concept of pointer in macro. just “replacing the string”
An question: What is the output of the following code?
#define macro_to_func(pp) ({printf("in Macro ...\n"); minus ;})
void do_something(int *a, int *b){
printf("do_something\n");
int c;
c = *a + *b;
printf("do_something %d \n", c);
}
int minus(int *a, int *b){
printf("minus\n");
int c;
c = *a - *b +1;
printf("minus a = %d \n", *a);
printf("minus b = %d \n", *b);
printf("minus %d \n", c);
return c;
}
int main()
{
int (*do_something)(int* c, int* d);
//printf("fptr 1 do_something %p\n", &do_something);
int m = -1;
int n = 7;
printf("do_something = macro_to_func\n");
do_something = macro_to_func(pp);
//printf("fptr minus %p\n", &minus);
//printf("fptr 2 do_something %p\n", &do_something);
if(do_something){
printf("in IF!!\n");
do_something(&m, &n); --------------------------->???
}
return 0;
}
Answer:
do_something = macro_to_func
in Macro …
in IF!!
minus
minus a = -1
minus b = 7
minus -7
Explanation: “int (*do_something)” is a local function pointer. In the macro, the macro_to_func will be replaced as “minus”, but do_something !!!
Copy link