#include
#include
// 定义log0函数,这里简化为仅打印日志
void log0(const char* file, const char* function, int line, int level, const char* format, ...) {
va_list args;
va_start(args, format);
printf("[%s:%s:%d] Level %d: ", file, function, line, level);
vprintf(format, args);
va_end(args);
}
#define mylog(level, ...) log0(__FILE__, __FUNCTION__, __LINE__, level, __VA_ARGS__)
int main() {
int x = 10;
mylog(1, "The value of x is %d\n", x); // 日志级别为1
return 0;
}
// 输出结果
[main.cpp:main:18] Level 1: The value of x is 10
#include
#include
#include
#include
void WriteFormatted ( const char * format, int ans,... )
{
va_list args;
va_start (args, format);
vprintf (format, args);
va_end (args);
if(ans == 6){
std::cout<<"end the function"<<std::endl;
}
}
int main ()
{
WriteFormatted("ans: %d-%d-%d\n",6,1,2,3);
WriteFormatted ("Call with %d variable argument.\n", 6,1);
WriteFormatted ("Call with %d variable %s.\n",6,2,"arguments");
return 0;
}
可变参数 举例说明
```cpp
#include
#include
#include
void print_args(int num, ...) {
va_list args;
va_start(args, num);
for (int i = 0; i < num; ++i) {
int arg = va_arg(args, int);
printf("%d ", arg);
}
va_end(args);
}
void function(const char* format, ...){
va_list args;
va_start(args, format);
vprintf(format, args);
va_end(args);
}
int main() {
// 可变参数demo
//打印出若干个整数 va_start --> va_arg --> va_end
print_args(3, 1, 2, 3);
//打印格式化内容 va_start --> vprintf --> va_end
// 注意 可变参数 后面不能再有参数 比如 function(const char* format, ..., std::string ans){...} 这样定义是错误的
function("\ntest:\n the person name is: %s\n", "zhangsan");
return 0;
}
1 2 3
test:
the person name is: zhangsan
可变参数参考1
可变参数参考2
可变参数参考3