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?)
Different programming languages have various ways to delineate the start and end points of a programming structure, such as a loop, method or conditional statement. For example, Java and C++ are often referred to as curly brace languages because curly braces are used to define the start and end of a code block.
Yes, it works, but only up to a single line just after an 'if' or 'else' statement. If multiple lines are required to be used then curly braces are necessary.
As for me, curly braces serve as a substitution for concatenation, they are quicker to type and code looks cleaner.
: either one of the marks { or } that are used as a pair around words or items that are to be considered together.
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With