Run the following codes:
Case 1:
#include <stdio.h>
int count=0;
void g(void){
printf("Called g, count=%d.\n",count);
}
#define EXEC_BUMP(func) (func(),++count)
typedef void(*exec_func)(void);
inline void exec_bump(exec_func f){
f();
++count;
}
int main(void)
{
//int count=0;
while(count++<10){
EXEC_BUMP(g);
//exec_bump(g);
}
return 0;
}
Case 2:
#include <stdio.h>
int count=0;
void g(void){
printf("Called g, count=%d.\n",count);
}
#define EXEC_BUMP(func) (func(),++count)
typedef void(*exec_func)(void);
inline void exec_bump(exec_func f){
f();
++count;
}
int main(void)
{
//int count=0;
while(count++<10){
//EXEC_BUMP(g);
exec_bump(g);
}
return 0;
}
Case 3:
#include <stdio.h>
int count=0;
void g(void){
printf("Called g, count=%d.\n",count);
}
#define EXEC_BUMP(func) (func(),++count)
typedef void(*exec_func)(void);
inline void exec_bump(exec_func f){
f();
++count;
}
int main(void)
{
int count=0;
while(count++<10){
//EXEC_BUMP(g);
exec_bump(g);
}
return 0;
}
Case 4:
#include <stdio.h>
int count=0;
void g(void){
printf("Called g, count=%d.\n",count);
}
#define EXEC_BUMP(func) (func(),++count)
typedef void(*exec_func)(void);
inline void exec_bump(exec_func f){
f();
++count;
}
int main(void)
{
int count=0;
while(count++<10){
EXEC_BUMP(g);
//exec_bump(g);
}
return 0;
}
The differences among the cases are defining a local variable or not, and using inline function vs. macro. Why the code above give different output? Besides, is there anyone can let me know why using the inline function are more efficient than macro.
Output below:
Case 1:
Called g, count=1.
Called g, count=3.
Called g, count=5.
Called g, count=7.
Called g, count=9.
Case 2:
Called g, count=1.
Called g, count=3.
Called g, count=5.
Called g, count=7.
Called g, count=9.
Case 3:
Called g, count=0.
Called g, count=1.
Called g, count=2.
Called g, count=3.
Called g, count=4.
Called g, count=5.
Called g, count=6.
Called g, count=7.
Called g, count=8.
Called g, count=9.
Case 4:
Called g, count=0.
Called g, count=0.
Called g, count=0.
Called g, count=0.
Called g, count=0.
count.