Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Whats the scope of a c function defined within objective-c class?

I was reading up about bypassing objective-c's messaging to gain performance (irrelevant to this specific question) when i found an interesting bit of code:

#import <Cocoa/Cocoa.h>

@interface Fib : NSObject { }

- (long long) cFib: (NSUInteger) number;

@end

@implementation Fib

// c implementation of fib
long long cFibIMP(NSUInteger number)
{
  return (number < 3) ? 1 : cFib(number - 1) + cFib(number - 2);
}

// method wrapper for c implementation of fib
- (long long) cFib: (NSUInteger) number
{
  return cFibIMP(number);
}

@end

My question is; when using c function, within an objective-c object, what scope is the c function (cFibIMP in this particular case) placed in? Does the objective-c class encapsulate the c function removing change of name-clash or is the c function simply dumped into the global scope of the whole objective-c program?

like image 276
Roja Buck Avatar asked Mar 20 '10 15:03

Roja Buck


People also ask

How the function can be defined in Objective-C?

A function is a group of statements that together perform a task. Every Objective-C program has one C function, which is main(), and all of the most trivial programs can define additional functions. You can divide up your code into separate functions.

Can you use C in Objective-C?

“Using C in Objective-C” is somewhat misleading, because Objective-C is a strict superset of the C language. You really can't use C in Objective-C, since Objective-C is C.

How do you define a class in Objective-C?

In Objective-C, classes are defined in two parts: An interface that declares the methods and properties of the class and names its superclass. An implementation that actually defines the class (contains the code that implements its methods)

What is @property in Objective-C?

The goal of the @property directive is to configure how an object can be exposed. If you intend to use a variable inside the class and do not need to expose it to outside classes, then you do not need to define a property for it. Properties are basically the accessor methods.


2 Answers

The functions are dumped in the "global" scope.

You can check this by adding a new class at the end of your sample code:

@interface Gib : NSObject {}
@end
@implementation Gib
- (void) t
{
    NSLog(@"%d", cFibIMP(10));
}
@end
like image 114
diciu Avatar answered Sep 19 '22 03:09

diciu


The C function has global scope.

If you want to have something like "class" scope, your best bet is probably to use the static keyword, which limits the scope of the function to the source file in which it is contained. For the sort of usage you're illustrating here, that's usually close enough.

like image 27
Stephen Canon Avatar answered Sep 19 '22 03:09

Stephen Canon