News for hackers. Stuff that matters.
Re:Few lesser known tricks, quirks and features of C by Joker_vD on Sunday February 19, 2023 @01:38PM (#34860432)
Never quite understood why compound literals are lvalues, but fine, whatever, I guess, it's so that you can write "&(struct Foo){};" instead of "struct Foo tmp; &tmp;"... which, on a tangential note, reminds me about Go: the proposals to make things like &5 and &true legal in Go were rejected because "the implied semantics would be unclear" even though &structFoo{} is legal and apparently has obvious semantics.
Re:Few lesser known tricks, quirks and features of C by leni536 on Sunday February 19, 2023 @02:41PM (#34861053)
In C compound literals have a relatively long lifetime compared to C++ temporaries. With these lifetime rules it makes sense that they are lvalues, although I like C++ rvalues (especially prvalues) more.

https://cigix.me/c17#6.5.2.5.p5

> If the compound literal occurs outside the body of a function, the object has static storage duration; otherwise, it has automatic storage duration associated with the enclosing block.

Re:Few lesser known tricks, quirks and features of C by cataphract on Sunday February 19, 2023 @03:53PM (#34861758)
It's useful when a function has a out or in/out struct parameter whose value at the end you're not interested in. Or in functions where the struct is an input parameter, but they return it as a return value too, which you can then assign to a pointer variable or immediately pass to another function.

Note that the struct values thus created have longer lifetimes than temporary C++ objects created directly inside the argument list of a function call.

Re:Few lesser known tricks, quirks and features of C by flohofwoe on Monday February 20, 2023 @07:37AM (#34867523)
That's extemely useful for invoking a function that takes a pointer to a struct:

   func(&(bla_t){ .x = 0, .y = 1 });
Re:Few lesser known tricks, quirks and features of C by gallier2 on Monday February 20, 2023 @09:15AM (#34868247)
Compound literals are anonymous variables, i.e. like variables except that there is no label visible in the C program. If you look at the assembly you'll see that they are declared exactly like a variable except with a compiler generated internal label.