9

enter image description here

While reading one of LLVM static analyzer documents, I stumbled upon a strange operator.

^{ int y = x; }();

I know I can define a nested block inside a function like { ... }, but can we even call it? Also, I've never seen any usage placing ^ in front of a curly bracket block. I thought this is kind of a language extension supported by GCC and googled this with keywords like anonymous function or lambda but was of no avail. Is there anyone who has any idea about this?

2

1 Answer 1

9

From Clang 9 Documentation Language Specification for Blocks it's a Block Literal Expression. It has the form of (from wiki):

^return_type ( parameters ) { function_body }

But:

If the return type is omitted and the argument list is ( void ), the ( void ) argument list may also be omitted.

The following:

^{ int y = x; }();

is equal to:

( ^void (void) { int y = x; } )();

is equal to:

void (^f)(void) = ^void (void) { int y = x; };
f();

It declares a block literal that does int y = x and immediately after declaring executes is.

4
  • Soooo this is a C++ lambda in C?
    – rubenvb
    Commented Feb 7, 2019 at 8:15
  • @rubenvb looks quite similar indeed Commented Feb 7, 2019 at 8:16
  • 1
    @rubenvb yes. I think only clang/llvm generally supports it. Generally, try not to use it, it isn't that popular. In C it's popular to write portable code. Gcc has extension blocks and local functions extensions, so you do lambda functions there differently.
    – KamilCuk
    Commented Feb 7, 2019 at 8:20
  • 2
    @KamilCuk It's popular if you write iOS or macOS code. Blocks shouldn't be used in cross-platform code though, as you say.
    – trojanfoe
    Commented Feb 7, 2019 at 10:52

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.