C++中避免使用宏定义常量或函数​的原因是什么

C++中避免使用宏定义常量或函数的原因是什么,针对这个问题,这篇文章详细介绍了相对应的分析和解答,希望可以帮助更多想解决这个问题的小伙伴找到更简单易行的方法。

ES.31:不要用宏定义常量或函数

Reason(原因)

Macros are a major source of bugs. Macros don't obey the usual scope and type rules. Macros don't obey the usual rules for argument passing. Macros ensure that the human reader sees something different from what the compiler sees. Macros complicate tool building.

宏是错误的主要来源之一。宏不会遵守通常的范围和类型准则。宏也不会遵守参数传递准则。宏为人提供一个和编译器视角有些不同的视角。宏让工具构建变得更复杂。

Example, bad(反面示例)

#define PI 3.14#define SQUARE(a, b) (a * b)

Even if we hadn't left a well-known bug in SQUARE there are much better behaved alternatives; for example:

虽然SQUARE定义中不存在已知的错误,但确实存在可以动作更好的其他选项。

constexpr double pi = 3.14;
template<typename T> T square(T a, T b) { return a * b; }

关于C++中避免使用宏定义常量或函数的原因是什么问题的解答就分享到这里了,希望以上内容可以对大家有一定的帮助,如果你还有很多疑惑没有解开,可以关注行业资讯频道了解更多相关知识。