As far as I can tell this is a compound literal, it is C99 feature, it is not standard C++ but both gcc and clang support it as an extension:
ISO C99 supports compound literals. A compound literal looks like a cast containing an initializer. Its value is an object of the type specified in the cast, containing the elements specified in the initializer; it is an lvalue. As an extension, GCC supports compound literals in C90 mode and in C++, though the semantics are somewhat different in C++.
Usually, the specified type is a structure. Assume that struct foo and
structure are declared as shown:
struct foo {int a; char b[2];} structure;
Here is an example of constructing a struct foo with a compound
literal:
structure = ((struct foo) {x + y, 'a', 0});
This is equivalent to writing the following:
{
struct foo temp = {x + y, 'a', 0};
struct
In this case the type of a
would pointer to int. Hopefully this was originally C code since as the gcc document says:
In C, a compound literal designates an unnamed object with static or automatic storage duration. In C++, a compound literal designates a temporary object, which only lives until the end of its full-expression.
and so taking the address in C++ is probably a bad idea since the lifetime of the object is over at the end of the full-expression. Although, it could have been C++ code which just relied on undefined behavior.
This is one of those cases where using the correct flags really helps a lot, in both gcc and clang using -pedantic will produce a warning and an error, for example gcc says:
warning: ISO C++ forbids compound-literals [-Wpedantic]
auto a = &(int) { 1 };
^
error: taking address of temporary [-fpermissive]
if we use -fpermissive
is gcc it indeed does allow this code to compile. I can not get clang to build this code with any flags in modern versions although old versions seem to allow it using -Wno-address-of-temporary
. I wonder if gcc allows this as a remnant of an old extension.
Note, the question Cryptic struct definition in C has a pretty interesting(depending on your definition of interesting) use of compound literals.
Assuming Schism is correct and this question is the original source then the use in that code in the example:
if (setsockopt(server_connection.socket, SOL_SOCKET, SO_REUSEADDR, &(int) { 1 }, sizeof(int)) < 0) {
is a valid use in both C99 and C++.