News for hackers. Stuff that matters.
Re:C++: zero-cost static initialization by naruhodo on Saturday July 19, 2025 @02:24AM (#44613065)
The rabbit hole I just went down is called C/C++ Statement Expressions [1] which are a GCC extension:

    #define FAST_STATIC(T) \
      *({ \
          \                                // statements separated by semicolons
          reinterpret_cast<T *>(ph.buf); \ // the value of the macro as a statement
       })
The reinterpret_cast<T*>(...) statement is a conventional C++ Expression Statement, but when enclosed in ({}), GCC considers the whole kit and kaboodle a Statement Expression that propagates a value.

There is no C equivalent, but in in C++, since C++11 you can achieve the same effect with lambdas:

    auto value = [](){ return 12345; }();
As noted in the linked SO discussion, this is analogous to a JS Immediately-Invoked Function Expression (IIFE).

[1] https://stackoverflow.com/questions/76890861/what-is-called-...

Re:C++: zero-cost static initialization by viralsink on Saturday July 19, 2025 @03:48AM (#44613437)
Lambdas are not fully equivalent since return statements in statement expressions will return at the function level, whereas return statements in lambdas will only return at the lambda level.
Re:C++: zero-cost static initialization by quibono on Saturday July 19, 2025 @06:06AM (#44614110)
Just for clarity, since I didn't understand on first reading.

    int foo() {
    int result = ({ 
        if (some_condition) 
            return -1;  // This returns from foo(), not just the statement expression
        42; 
    });
    // This line might never be reached
}