Macros Compared To Functions

Virtually all programming languages have functions of some sort (whether they are called functions, procedures, subprograms, methods, messages, routines, or even processes); the function is a concept derived from mathematics and a good way to factor out commonality. Many (though not all) programming languages also have macros (some, like CeePlusPlus, have multiple macro systems - C++ has two; one type of macro is introduced with #define, the other type with template<>).

Functions are not a controversial feature (though some in the OO camp feel that they should be made subservient to objects; nobody suggests getting rid of them.) Macros are a bit more controversial; many computer scientists are known to dislike and distrust "preprocessors". Much of this has to do with the CeePreprocessor, widely regarded as one of the worst macro processors in widespread use. Other programmers, particularly those from a Lisp background, love macros - and both CommonLisp and SchemeLanguage have very powerful (though differing) macro systems.

This page lists key differences between functions (including "member functions" in OO languages) and macros (including CeePlusPlus templates).

 #define begin {
 #define end }

Obviously, begin and end in isolation are not well-formed program fragments; consisting of unbalanced curly braces. Used together, they are fine. Functions certainly cannot do this sort of thing.

Are macros only for efficiency?

No; since macros work at the syntactical or lexical level; they can be used in contexts where functions cannot; and can accept arguments that functions cannot. Use of macros solely for efficiency is probably an AntiPattern - at least in more modern languages that either support inline declarations or perform inlining as an optimization.

My personal opinion: Use functions when you can, macros when you have to. However, there are times when you have to; so eliminating macros entirely weakens a language. That said, many powerful languages have no macro facility whatsoever.

In addition to the usual gripes about the CeePreprocessor, BertrandMeyer makes some arguments against macros in ObjectOrientedSoftwareConstruction. Don't have my copy handy at the moment... WillFillInLater?.

View edit of January 22, 2010 or FindPage with title or text search