01 January 2006

In C programming language, macro is kind of notorious. Fortunately, we have alternative solutions in many cases. But there are still people who prefer macro as they may not aware of the risks of using macro. Therefore, I would like to list some in this post.

  • Side effects

    If a expression passed to macros has side effects, the outcome might be unexpected:

    #define POWER(x) (x)(x)
    int i = 1;
    SQUARE(++i); // bug
    SQUARE(i++); // bug even subtle

    In C++, we may use either inline functions or templates instead.

    # inline function version
    inline int mySquare(const int i){return ii;}
    # template version
    template T mySquare(cosnt T& i){return ii;}
  • Lack of grammar check

    In many implementations of stdio.h, getchar and putchar are defined macros. The error in the following code snippet is that putchar is provided with no parameter. But, can you tell that from compilation error message?

    /* test.c */
    #include <stdio.h> /* In stdio.h #define putchar(x) putc(x, stdout) */
    int main()
        putchar ();
        return 0;
    $ gcc test.c
    test.c: In function `main':
    test.c:5: error: parse error before ',' token
    $ gcc --version test.c
    gcc (GCC) 3.4.4 (cygming special) (gdc 0.12, using dmd 0.125)
    Copyright (C) 2004 Free Software Foundation, Inc.
    This is free software; see the source for copying conditions.  There is NO
  • Cannot single-step debug
  • Cross-reference tools cannot handle/expand macros

Is not protected by namespace

namespace na
    #define NUM 1
namespace nb
    #define NUM 2

blog comments powered by Disqus