2

Can I declare ObjC block with auto?

auto fun = ^(int x) { NSLog(@"%d", x); }
fun(5);

I cannot work out valid syntax for that.

Yakk - Adam Nevraumont
  • 262,606
  • 27
  • 330
  • 524
Wojtek
  • 239
  • 1
  • 2
  • 12
  • 3
    I suspect **if** it works, it will only work with Objective-C++, as `auto` means something different in C. – trojanfoe Jan 15 '13 at 13:20
  • Apparently there's a different meaning in C++0x, where previous C++ specs used `auto` from C (which is just the default storage type). Unless there's a reason that's out of scope of this question, I would encourage not using `auto` at all in this case, preferring `int (^fun)(int) =`. (As an Objective-C developer, I've never used `auto`, and would likely need to explain it to all my coworkers.) – wjl Jun 06 '13 at 01:39

3 Answers3

4

You are missing a ; after the declaration of fun. Otherwise, you got the syntax right, and Clang will accept that in -std=c++11 -fblocks mode, for C++ or Objective-C++ input. (Note that blocks are actually an orthogonal extension which is not part of Objective-C.)

Richard Smith
  • 13,696
  • 56
  • 78
0

I don't think the auto keyword from C++/Objective-C++ is used in objective-C.

As for declaring block variable for your example the following will work in objective-C

void(^fun)(int x) = ^(int x) {
NSLog(@"%d",x);
};

fun(5);

For more declaration options on block there's a very good answer here

Community
  • 1
  • 1
Eric Genet
  • 1,260
  • 1
  • 9
  • 19
0

The auto keyword is a c++11 keyword. Objective-c is a superset of c not c++ and therefor does not contain the properties of c++, but rather c. As for objective-c++, I do not believe that clang is up to date on all of the new c++11 features, especially in the compiler that builds objective-c++. Hope this helps!

NSNolan
  • 1,025
  • 1
  • 13
  • 18
  • 2
    Objective-C is a set of extensions which can be added to either C or C++. Clang has a pretty comprehensive C++11 implementation (only missing a couple of features), and the same compiler is used for C++ and Objective-C++. – Richard Smith Mar 10 '13 at 03:17