I'm using a nice GCC extensions which allow us to declare VLAs inside structures. For now I found a way to pass VLAs to functions (by value) this way. I also find a way to return one but in a very limited context.
The function code of this example is this:
extern void func3()
{
size_t size;
scanf("%zu", &size);
struct tx{int _[size];} fn()
{
struct tx rt;
for(size_t i=0; i < size; ++i)
scanf("%d", &rt._[i]);
return rt;
}
volatile __typeof__(fn) *pf = fn;
}
The above example is designed for test purposes (specifically to compare binary code compiled of it).
However this is quite limited as the size of returned array doesn't vary between different calls of the function.
How could I make the returned array size equal either to one of the function parameters or some other local in this function.
I don't think alloca
could help me in the case as the memory it allocates is immediately destroyed at function exit (IRC).
I want to write something like this:
/*???*/ func5()
{
size_t size;
scanf("%zu", &size);
struct {int _[size];} rt;
for(size_t i=0; i < size; ++i)
scanf("%d", &rt._[i]);
return rt; //ok - return the structure
}
In other words what could be the type inside the question marks? Or maybe there is other solution (but without using malloc
)?
Theoretical usage of such function will theoretically need another type to store the returned value as the size of the returned structure won't be available to the caller(unless there is someway to avoid this?). But on first sight it should be something like this:
size_t size;
//scanf("%zu", &size);
struct {int _[size];} tmp; //create locally VM type
//compatible with the one
//returned by our theoretical func5
//we can't directly initialize tmp here (gcc complains)
tmp = ((__typeof__(tmp) (*)())func5)(); //direct assignment between VM structures
//works here on the other hand
//as function return value is rvalue and we can't
//take its pointer and cast it to our local VM structure type
//we instead cast the function pointer
If we do something like this:
__typeof__(func5()) tmp = func5();
It wouldn't work because the VM return-type of func5
will either depend on it's arguments or local variables.
However that's all theoretical for the moment as we still can't define this function.