In C, there is a feature called Variadic functions. This feature is almost equivalent to C# params except that you have to give the params size or something like that, which is because of the nature of low level array in C.
#include <stdio.h>
#include <stdarg.h>
void use_params(int number_of_params, ...) {
va_list args;
va_start(args, number_of_params);
for(int i = 0; i < number_of_params; ++i) {
some_type element = va_arg(args, some_type);
do_something_with(element);
}
va_end(args);
}
void main() {
use_params(4, 'a', 'b', 'c', 'd');
}
This way is the best option about either performance or flexibility (you can have multiple params of multiple types).
But if you do not love using va_list
, va_start
,... and prefer something easier to read, std::vector
is where to go. Note that std::vector
is a C++ feature, so it will be not available if your system supports only C, in which variadic functions is the only choice.
#include <iostream>
#include <vector>
void use_params(const std::vector<int>& params) {
for(size_t i = 0; i < params.size(); ++i) {
do_something_with(params[i]);
}
}
void main() {
use_params({1, 2, 3, 5});
}