I wonder how can I tease out an array in C to several arguments of a function. After I saw the amazing syntatic sugar from Go (golang) I thinking about it.
The c code:
#include <stdio.h>
#include <stdarg.h>
// assert: all args are valid ints
void printEach(int len, ...) {
// Irrelevant, this function print their arguments
// And I know how to use va_start, va_arg...
}
void handleVet(int* v, int n) {
// **HERE is my the question!!!**
printEach(n, v[0]...[n]) // <----------- NON-C code. I need it.
}
int main(void) {
int v[] = {12,14,15,15};
//I can do that only because the vector is static. I know the len when I'm coding
printEach(4, v[0],v[1],v[2],v[3]);
// But if we imagine an arbitrary vector, we got a problem
handleVet(v, 4);
return 0;
}
By Example, in go it would be:
package main
import "fmt"
func printEach (v ...int64) {
// Irrelevant, this function print their arguments
}
func main() {
var arr []int64 = []int64{1,14,15,}
printEach(arr...)
}
How can I achieve the same effect of "printEach(arr...)" in C?
This is a rudimentary example on how vararg is working in C. I wasn't able to take refference to your go example as I don't udnerstand what your code does. I hope this minimal example is clear enough. If you have any questions ask me and I will edit it in.
void Foo(size_t sizeParamAmount, char *types, ...);
void Foo(size_t sizeParamAmount, char *types, ...)
{
size_t i;
float fTmp;
int iTmp;
va_list vlArgList;
va_start (vlArgList, sizeParamAmount);
for (i= 0; i< sizeParamAmount; i++)
{
switch (types[i])
{
case 'i':
iTmp = va_arg (vlArgList, int));
break;
case 'f':
fTmp = va_arg (vlArgList, float));
break;
default:
return;//error
}
}
va_end(vlArgList);
}
After reading your edit:
As I already did in my minimal example, you can hand in a pointer before the var_arg's which is explaining which argument is of what type. so you could call Foo
this way:
Foo (3, "ifi", 3, 5.973, 92);
And after reading your comment to another answer I got what you are asking about.
In that case you really jsut should hand in a pointer (or array without []
behaves for this case the same) which holds an end content token.
Anyway there is a way. but you had to freak around with preprocessing tokens.
And would be totally over the top for your needs. This answer would anyway give you the requested notation. you had to set for PRED a limit by sizeof(yourarray) and the let OP take the single elements.
https://stackoverflow.com/a/10542793/2003898
But there is sadly not a more minimal example.
You will need to specify the size of the array. Here's what it might look like:
void printEach(int* values, int size)
{
if(size==0)
return;
printf("%d", value[0]);
printEach(values+1, size-1);
}
You are looking for Variadic function, you should look at stdarg.h and varargs.h