ltWolfik
ltWolfik

Reputation: 330

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.

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

Upvotes: 22

Views: 5395

Answers (4)

ad absurdum
ad absurdum

Reputation: 21320

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.

Upvotes: 19

Jonatan Goebel
Jonatan Goebel

Reputation: 1139

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.

Upvotes: 1

Horia Coman
Horia Coman

Reputation: 8781

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.

Upvotes: 0

Johannes Mols
Johannes Mols

Reputation: 1041

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

Upvotes: 0

Related Questions