#include <stdarg.h>
// Java的可变参数:int...
// C++的可变参数写法:...
void sum(int count, ...) {
va_list vp;
va_start(vp, count); // 获取参数列表的指针
for (int i = 0; i < count; ++i) { // 依次获取每个参数
int r = va_arg(vp, int);
LOGI("%d", r)
}
va_end(vp); // 结束参数列表的处理
}
int main() {
sum(3, 7, 8, 9);
return 0;
}
Compared with Java, C/C++'s variable parameters are a bit more complicated to use. When defining parameters on a method, directly use ... to represent variable parameters.
How to use it in the method? Use va_start to get the pointer of the parameter list, and then use va_arg to get the value of the corresponding parameter. After getting it, you need va_end to close the pointer.
In java, if the array or collection crosses the boundary, an exception will be thrown, but C/C++ will not, and the system value (garbled characters) will be printed out, so when using pointers in C/C++, it is necessary to operate the pointer accurately and correctly, so as not to appear unexpected error