The following code compiles:
^{}();
And this compiles:
void (^x)();
(x = ^{})();
But this doesn’t:
(void (^x)() = ^{})();
The error I get is Expected ')'. Is this a bug with llvm or something? It’s totally holding me back from pretending Objective-C is JavaScript.
This wouldn’t make sense in a C-like language. To see why, let’s build the statement from the ground up.
First, we’ll use your working declaration for
x:Now let’s initialize it in the same statement:
So far so good –
xhas been initialized with the correct block. So let’s invokexnow. But where will the()go? Naturally, we need to place the()immediately after a block-valued expression. However, in C, declarations are statements, not expressions sodoesn’t make sense. The only place the
()can go is after the^{}:But
^{}()has typevoid, not typevoid (^)().To sum up: you can’t declare a block variable and invoke it at the same time. you’ll have to either declare and initialize the variable, and then call it
or declare it and then assign and call it
or just separate all three:
As a concluding thought, let’s say it was desirable to declare and invoke blocks at the same time. If we decided to allow code like
(void (^x)() = ^{})();, then for the sake of consistency, we would have to also allow code such as++(void x = 4);or(void x = 1) + (void y = 2);. I hope you’ll agree that these just look strange in C.