Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass brace enclosed initializer list as an argument?

Tags:

c

function

This is a copy of the this post: Brace Enclosed Initializer List As Function Argument, though I am looking for a solution using only methods available in C. I am using the Windows 8 compiler.

Basically, I'm looking to do something like this:

HANDLE hThread1 = CreateThread(...);
HANDLE hThread2 = CreateThread(...);
HANDLE hThread3 = CreateThread(...);

...

WaitForMultipleObjects( 3, {hThread1,hThread2,hThread3}, FALSE, INFINITE );

instead of this:

HANDLE hThread[3];
hThread[0] = CreateThread(...);
hThread[1] = CreateThread(...);
hThread[2] = CreateThread(...);

...

WaitForMultipleObjects( 3, hThread, FALSE, INFINITE );



foo(arg1, arg2, {arg3_1, arg3_2});
like image 835
wanovak Avatar asked Jun 29 '12 20:06

wanovak


1 Answers

C99 provides compound literals, which would give you what you want:

WaitForMultipleObjects( 3,
                        (HANDLE*){hThread1, hThread2, hThread3},
                        FALSE,
                        INFINITE );

Unfortunately, Microsoft has said that they have no interest in supporting any C standard past C90, except for those features that happen to be part of C++ (and C++ doesn't have compound literals).

You could write a variadic function that builds an array of HANDLEs and returns a pointer to its first element. A call then might look like:

WaitForMultipleObjects( 3,
                        HandleList(3, hThread1, hThread2, hThread3),
                        FALSE,
                        INFINITE );

But then you have the usual problems of managing the memory allocated for the array.

C90 doesn't provide a particularly clean way of doing what you want.

like image 140
Keith Thompson Avatar answered Nov 07 '22 18:11

Keith Thompson