Macro vs Function in C

2019-01-02 22:09发布

I always saw examples and cases where using a macro is better than using function.

Could someone explain me with an example the disadvantage of a macro compared to a function?

10条回答
霸刀☆藐视天下
2楼-- · 2019-01-02 22:37

I did not notice, in the answers above, one advantage of functions over macros that I think is very important:

Functions can be passed as arguments, macros cannot.

Concrete example: You want to write an alternate version of the standard 'strpbrk' function that will accept, rather than an explicit list of characters to search for within another string, a (pointer to a) function that will return 0 until a character is found that passes some test (user-defined). One reason you might want to do this is so that you can exploit other standard library functions: instead of providing an explicit string full of punctuation, you could pass ctype.h's 'ispunct' instead, etc. If 'ispunct' was implemented only as a macro, this wouldn't work.

There are lots of other examples. For example, if your comparison is accomplished by macro rather than function, you can't pass it to stdlib.h's 'qsort'.

An analogous situation in Python is 'print' in version 2 vs. version 3 (non-passable statement vs. passable function).

查看更多
迷人小祖宗
3楼-- · 2019-01-02 22:40

Macro features:

  • Macro is Preprocessed
  • No Type Checking
  • Code Length Increases
  • Use of macro can lead to side effect
  • Speed of Execution is Faster
  • Before Compilation macro name is replaced by macro value
  • Useful where small code appears many time
  • Macro does not Check Compile Errors

Function features:

  • Function is Compiled
  • Type Checking is Done
  • Code Length remains Same
  • No side Effect
  • Speed of Execution is Slower
  • During function call, Transfer of Control takes place
  • Useful where large code appears many time
  • Function Checks Compile Errors
查看更多
Explosion°爆炸
4楼-- · 2019-01-02 22:47

No type checking of parameters and code is repeated which can lead to code bloat. The macro syntax can also lead to any number of weird edge cases where semi-colons or order of precedence can get in the way. Here's a link that demonstrates some macro evil

查看更多
We Are One
5楼-- · 2019-01-02 22:48

Adding to this answer..

Macros are substituted directly into the program by the preprocessor (since they basically are preprocessor directives). So they inevitably use more memory space than a respective function. On the other hand, a function requires more time to be called and to return results, and this overhead can be avoided by using macros.

Also macros have some special tools than can help with program portability on different platforms.

Macros don't need to be assigned a data type for their arguments in contrast with functions.

Overall they are a useful tool in programming. And both macroinstructions and functions can be used depending on the circumstances.

查看更多
在下西门庆
6楼-- · 2019-01-02 22:52

Example 1:

#define SQUARE(x) ((x)*(x))

int main() {
  int x = 2;
  int y = SQUARE(x++); // Undefined behavior even though it doesn't look 
                       // like it here
  return 0;
}

whereas:

int square(int x) {
  return x * x;
}

int main() {
  int x = 2;
  int y = square(x++); // fine
  return 0;
}

Example 2:

struct foo {
  int bar;
};

#define GET_BAR(f) ((f)->bar)

int main() {
  struct foo f;
  int a = GET_BAR(&f); // fine
  int b = GET_BAR(&a); // error, but the message won't make much sense unless you
                       // know what the macro does
  return 0;
}

Compared to:

struct foo {
  int bar;
};

int get_bar(struct foo *f) {
  return f->bar;
}

int main() {
  struct foo f;
  int a = get_bar(&f); // fine
  int b = get_bar(&a); // error, but compiler complains about passing int* where 
                       // struct foo* should be given
  return 0;
}
查看更多
来,给爷笑一个
7楼-- · 2019-01-02 22:57

When in doubt, use functions (or inline functions).

However answers here mostly explain the problems with macros, instead of having some simple view that macros are evil because silly accidents are possible.
You can be aware of the pitfalls and learn to avoid them. Then use macros only when there is a good reason to.

There are certain exceptional cases where there are advantages to using macros, these include:

  • Generic functions, as noted below, you can have a macro that can be used on different types of input arguments.
  • Variable number of arguments can map to different functions instead of using C's va_args.
    eg: https://stackoverflow.com/a/24837037/432509.
  • They can optionally include local info, such as debug strings:
    (__FILE__, __LINE__, __func__). check for pre/post conditions, assert on failure, or even static-asserts so the code won't compile on improper use (mostly useful for debug builds).
  • Inspect input args, You can do tests on input args such as checking their type, sizeof, check struct members are present before casting
    (can be useful for polymorphic types).
    Or check an array meets some length condition.
    see: https://stackoverflow.com/a/29926435/432509
  • While its noted that functions do type checking, C will coerce values too (ints/floats for example). In rare cases this may be problematic. Its possible to write macros which are more exacting then a function about their input args. see: https://stackoverflow.com/a/25988779/432509
  • Their use as wrappers to functions, in some cases you may want to avoid repeating yourself, eg... func(FOO, "FOO");, you could define a macro that expands the string for you func_wrapper(FOO);
  • When you want to manipulate variables in the callers local scope, passing pointer to a pointer works just fine normally, but in some cases its less trouble to use a macro still.
    (assignments to multiple variables, for a per-pixel operations, is an example you might prefer a macro over a function... though it still depends a lot on the context, since inline functions may be an option).

Admittedly, some of these rely on compiler extensions which aren't standard C. Meaning you may end up with less portable code, or have to ifdef them in, so they're only taken advantage of when the compiler supports.


Avoiding multiple argument instantiation

Noting this since its one of the most common causes of errors in macros (passing in x++ for example, where a macro may increment multiple times).

its possible to write macros that avoid side-effects with multiple instantiation of arguments.

C11 Generic

If you like to have square macro that works with various types and have C11 support, you could do this...

inline float           _square_fl(float a) { return a * a; }
inline double          _square_dbl(float a) { return a * a; }
inline int             _square_i(int a) { return a * a; }
inline unsigned int    _square_ui(unsigned int a) { return a * a; }
inline short           _square_s(short a) { return a * a; }
inline unsigned short  _square_us(unsigned short a) { return a * a; }
/* ... long, char ... etc */

#define square(a)                        \
    _Generic((a),                        \
        float:          _square_fl(a),   \
        double:         _square_dbl(a),  \
        int:            _square_i(a),    \
        unsigned int:   _square_ui(a),   \
        short:          _square_s(a),    \
        unsigned short: _square_us(a))

Statement expressions

This is a compiler extension supported by GCC, Clang, EKOPath & Intel C++ (but not MSVC);

#define square(a_) __extension__ ({  \
    typeof(a_) a = (a_); \
    (a * a); })

So the disadvantage with macros is you need to know to use these to begin with, and that they aren't supported as widely.

One benefit is, in this case, you can use the same square function for many different types.

查看更多
登录 后发表回答