Reputation: 10172
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
Reputation: 104698
#define
is useful for:
#include
C and C++ headers, #import
ObjC headers)UIKIT_EXTERN
) which must be resolved during preprocessing.NS_AVAILABLE_IOS()
) which must be resolved during preprocessing.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
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