rptwsthi
rptwsthi

Reputation: 10172

What are the pros and cons of macros (#define) in objective C?

I wonder if macros only have pros in any programming language. As there must be the limit we can create macros, and in frequency of use.

Suppose we create 100 macros in a class and imported that in 100 class of an application project. Is this a right approach?

Upvotes: 0

Views: 1351

Answers (2)

justin
justin

Reputation: 104698

#define is useful for:

  • header include guards for C and C++ headers (idiom: #include C and C++ headers, #import ObjC headers)
  • conditional compilation for language compatibility (e.g. UIKIT_EXTERN) which must be resolved during preprocessing.
  • conditional compilation for platform/compiler/version specific declarations (e.g. NS_AVAILABLE_IOS()) which must be resolved during preprocessing.
  • Assertion macros. Specifying the information such as the file, line and expression is just too noisy and error-prone.

for everything else, there is an alternative which will save you headaches along the way.

Suppose we create 100 macros in a class and imported that in 100 class of an application project. Is this a right approach?

no - that is terrifying :)

Cons

There are many. Too often, the program will be difficult to understand by humans and programs (compiler, parser, indexer) alike. It's a good way to introduce bugs, and completely replace text of unrelated programs (via a simple #import). There are more modern replacements for pretty much everything (e.g. functions, inline, typedef, constants, enums) -- Allow the compiler to make your life easier!

Upvotes: 2

Analog File
Analog File

Reputation: 5316

#define is a preprocessor macro. You do not create macro in a class as the macro is textually expanded on use but it's definition is not part of the class even if you happen to lexically write it within the class.

Also you do not import a class in other classes, you import the class declaration header. Imports only happen once per compilation unit even if you specify them multiple times. Therefore you'd still have at most one declaration of each macro in each compilation unit, and since macros are preprocessor only it'll only be there during the early phases of compilation.

You are not saying exactly what you want to use the macros for, therefore it's hard to say if they are the best solution for you or if you have a better alternative. But I would not worry about their number. The standard header files define hundreds of macros.

Upvotes: 2

Related Questions