//C 没有可选参数,也没有重载:
//选项装在结构体里传递,字段为零表示“默认值”
typedef struct {
const char *message; //nullptr: "Goodbye!"
int times; //0:一次
} GoodbyeOptions;
void sayGoodbyeWith(GoodbyeOptions options) {
const char *message = options.message != nullptr ? options.message :
"Goodbye!";
int times = options.times > 0 ? options.times : 1;
for (int i = 0; i < times; i++) {
printf("%s\n", message);
}
}
//宏用具名字段构造结构体:未指定的字段为零;
//默认值不写进宏里,
//否则再次设置该字段的调用方会收到警告 -Woverride-init
#define sayGoodbye(...) sayGoodbyeWith((GoodbyeOptions){__VA_ARGS__})
sayGoodbye();
//输出 "Goodbye!"
sayGoodbye(.message = "see you");
//输出 "see you"
sayGoodbye(.times = 2, .message = "bye");
//输出 "bye" 两次