//macro.cpp
#include <iostream>
using namespace std;
#define getAvgTime(x) ({ \
x+10; \ //千万不要写成return x+10;g++编译器会报错
})
int main() {
int x = 10, y=0;
y =getAvgTime(x);
cout <<"x = " << x <<", y = " << y <<endl;
return 0;
}
其他写法:
#define getAvgTime(x,ts) \
({ \
static uint64_t stat_##x##_avg_dur = 0; \
static uint64_t stat_##x##_count = 0; \
static uint64_t stat_total_##x##_dur = 0; \
int64_t retValue = 0; \
if (ts < 1000) { \
stat_##x##_count++; \
stat_total_##x##_dur += ts; \
stat_##x##_avg_dur = stat_total_##x##_dur / stat_##x##_count; \
retValue = stat_##x##_avg_dur; \
} else { \
retValue = -1; \
} \
retValue; \ //不要写return retValue, 可使用(?:)的方式。
)
})
int64_t avg_init_t = getAvgTime(Init, init_time);
注意返回值应包含在({})中,如#define get(x) ({x>10?x:-1})