Why are C macros not type-safe?

后端 未结 7 1751
礼貌的吻别
礼貌的吻别 2021-02-18 16:01

If have encountered this claim multiple times and can\'t figure out what it is supposed to mean. Since the resulting code is compiled using a regular C compiler it will end up b

7条回答
  •  醉话见心
    2021-02-18 16:13

    There are situations where macros are even less type-safe than functions. E.g.

    void printlog(int iter, double obj)
    {
        printf("%.3f at iteration %d\n", obj, iteration);
    }
    

    Calling this with the arguments reversed will cause truncation and erroneous results, but nothing dangerous. By contrast,

    #define PRINTLOG(iter, obj) printf("%.3f at iteration %d\n", obj, iter)
    

    causes undefined behavior. To be fair, GCC warns about the latter, but not about the former, but that's because it knows printf -- for other varargs functions, the results are potentially disastrous.

提交回复
热议问题