简体   繁体   中英

Curly braces as argument of function

I've noticed in some source code the line:

if(pthread_create((pthread_t[]){}, 0, start_thread, pthread_args)) {
...

It works correctly, but how to understand the first argument? It seems, that curly braces converts to pthread_t[] type.

Ps I googled, but didn't find answer, only some guesses (some form of initialization, or legacy feature of c?)

This is a compound literal , with a constraint violation since initializer braces cannot be empty :

(pthread_t[]){}

Using gcc -std=c99 -Wall -Wextra -Wpedantic this produces the warning:

compound_literal_pthread.c:6:36: warning: ISO C forbids empty initializer braces [-Wpedantic]
     pthread_t *ptr = (pthread_t []){};

The result seems to be a pointer to pthread_t , though I don't see this behavior documented in the gcc manual. Note that empty braces are allowed as initializers in C++, where they are equivalent to { 0 } . This behavior seems to be supported for C, but undocumented, by gcc. I suspect that is what is happening here, making the above expression equivalent to:

(pthread_t[]){ 0 }

On my system, pthread_t is a typedef for unsigned long , so this expression would create an array of pthread_t containing only a 0 element. This array would decay to a pointer to pthread_t in the function call.

It's a compound literal as mentioned by @some-programmer-dude.

In this specific case it is use to create an array to store the thread_id and discharge it later without the need of creating an extra variable. That is necessary because pthread_create does not accept NULL as argument for thread_id .

You're creating an array with pthread[] . You can pass values in the curly braces if you define a length for the argument.

What you're dealing with there is an array initializer, which happens to be the empty array. You'd usually find it as:

int my_array[] = (int[]){10, 20, 30};

And it would initialize my_array to contain three elements. Here there are no elements, hence the awkward syntax.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM