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?
1
#define macro_to_func(pp) ({printf("in Macro ...\n"); minus ;})
2
3
void do_something(int *a, int *b){
4
printf("do_something\n");
5
int c;
6
c = *a + *b;
7
printf("do_something %d \n", c);
8
}
9
10
int minus(int *a, int *b){
11
printf("minus\n");
12
int c;
13
c = *a - *b +1;
14
printf("minus a = %d \n", *a);
15
printf("minus b = %d \n", *b);
16
printf("minus %d \n", c);
17
return c;
18
}
19
20
int main()
21
{
22
int (*do_something)(int* c, int* d);
23
//printf("fptr 1 do_something %p\n", &do_something);
24
25
int m = -1;
26
int n = 7;
27
28
printf("do_something = macro_to_func\n");
29
do_something = macro_to_func(pp);
30
//printf("fptr minus %p\n", &minus);
31
//printf("fptr 2 do_something %p\n", &do_something);
32
if(do_something){
33
printf("in IF!!\n");
34
do_something(&m, &n); --------------------------->???
35
}
36
return 0;
37
}
Copied!
Answer:
1
do_something = macro_to_func
2
in Macro …
3
in IF!!
4
minus
5
minus a = -1
6
minus b = 7
7
minus -7
Copied!
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