Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Curly braces as argument of function

Tags:

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?)

like image 446
ltWolfik Avatar asked May 31 '17 11:05

ltWolfik


People also ask

What is the function of curly braces?

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.

Are curly braces required around the statements in a function?

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.

What is the significance of curly braces in string handling?

As for me, curly braces serve as a substitution for concatenation, they are quicker to type and code looks cleaner.

What do curly brackets mean?

: either one of the marks { or } that are used as a pair around words or items that are to be considered together.


Video Answer


2 Answers

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.

like image 151
ad absurdum Avatar answered Oct 21 '22 00:10

ad absurdum


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.

like image 38
Jonatan Goebel Avatar answered Oct 20 '22 23:10

Jonatan Goebel