Why are preprocessor macros evil and what are the alternatives?

前端 未结 8 2153
面向向阳花
面向向阳花 2020-11-22 02:46

I have always asked this but I have never received a really good answer; I think that almost any programmer before even writing the first \"Hello World\" had encountered a p

8条回答
  •  星月不相逢
    2020-11-22 03:04

    Macros are valuable especially for creating generic code (macro's parameters can be anything), sometimes with parameters.

    More, this code is placed (ie. inserted) at the point of the macro is used.

    OTOH, similar results may be achived with:

    • overloaded functions (different parameter types)

    • templates, in C++ (generic parameter types and values)

    • inline functions (place code where they are called, instead of jumping to a single-point definition -- however, this is rather a recommandation for the compiler).

    edit: as for why the macro are bad:

    1) no type-checking of the arguments (they have no type), so can be easily misused 2) sometimes expand into very complex code, that can be difficult to identify and understand in the preprocessed file 3) it is easy to make error-prone code in macros, such like:

    #define MULTIPLY(a,b) a*b
    

    and then call

    MULTIPLY(2+3,4+5)
    

    that expands in

    2+3*4+5 (and not into: (2+3)*(4+5)).

    To have the latter, you should define:

    #define MULTIPLY(a,b) ((a)*(b))
    

提交回复
热议问题