面试题答案
一键面试- 宏定义:
#include <stdio.h>
// 定义宏用于输出函数入口信息
#define DEBUG_ENTRY(func) do { \
printf("Entering function %s\n", func); \
} while(0)
// 定义宏用于输出函数出口信息
#define DEBUG_EXIT(func) do { \
printf("Exiting function %s\n", func); \
} while(0)
- 使用示例:
void testFunction() {
DEBUG_ENTRY(__func__);
// 函数具体逻辑
printf("Inside testFunction\n");
DEBUG_EXIT(__func__);
}
int main() {
testFunction();
return 0;
}
在上述代码中,__func__
是C语言的内置标识符,它会被自动替换为当前所在函数的名字。DEBUG_ENTRY
和 DEBUG_EXIT
宏分别用于输出函数的入口和出口信息。do { ... } while(0)
结构用于确保宏在各种上下文中(如 if - else
语句中)都能正确工作。