Why are C macros not type-safe?

2020-06-30 05:26发布

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 being type checked just as much (or little) as any other code.

So why are macros not type safe? It seems to be one of the major reasons why they should be considered evil.

标签: c++ c types macros
7条回答
祖国的老花朵
2楼-- · 2020-06-30 06:08

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.

查看更多
登录 后发表回答