Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can a C function be defined within an Objective-C method?

Tags:

c

objective-c

I have a method, like so:

- (void) simpleMethod {
    var = someValue;
}

I wanted to define a function which exists only within that method (I can do this in python for example). I tried to define it like a normal C function, like this...

- (void) simpleMethod {
    var = someValue;
    int times1k(int theVar) {
    return theVar * 1000;
    }
    ivar = times1k(var);
}

But Xcode throws various errors. Is it possible to define a function within a method in Objective-C? And if so, how?

like image 944
Rik Smith-Unna Avatar asked May 11 '26 19:05

Rik Smith-Unna


1 Answers

No, Objective-C follows the strict C rules on this sort of thing, so nested functions are not normally allowed. GCC allowed them via a language extension but this extension has not been carried over to Clang and the modern toolchain.

What you can do instead is use blocks, which are Objective-C's version of what Python (and most of the rest of the world) calls closures. The syntax is a little funky because of the desire to remain a superset of C, but your example would be:

- (void) simpleMethod {
    var = someValue;

    // if you have a bunch of these, you might like to typedef
    // the block type
    int (^times1k)(int) = ^(int theVar){
    return theVar * 1000;
    };

    // blocks can be called just like functions
    ivar = times1k(var);
}

Because that's a closure rather than a simple nested function there are some rules you'd need to follow for declaring variables if you wanted them not to be captured at their values when the declaration is passed over, but none that are relevant to your example because your block is purely functional. Also times1k is a variable that you can in theory pass about, subject to following some unusual rules about memory management (or letting the ARC compiler worry about them for you).

For a first introduction to blocks, I like Joachim Bengtsson's article.

like image 129
Tommy Avatar answered May 14 '26 09:05

Tommy



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!