首页 > 解决方案 > Deitel 和 Deitel 所说的“不应将具有副作用的表达式传递给宏”是什么意思?

问题描述

我对图像的红色标记部分有这些疑问?图片摘自 Deitel & Deitel C++ 附录 E:预处理器

  1. 当我们说“有副作用的表达式”时,它是什么意思?

  2. 我认为作者的目的是我们不应该改变宏替换中存在的变量的值,对吗?

  3. 我根本不明白关于常见错误的部分。你能用代码解释一下吗?

摘自 Deitel & Deitel C++ 附录 E:预处理器

标签: c++macros

解决方案


What does it mean when we say " Expressions with side effects" ?

Expressions like ++a. If you have something like #define max(a, b) ((a) > (b) ? (a) : (b)) and if you do max(++foo, bar), this macro expands to (++foo) > (bar) ? (++foo) : (bar), which possibly increments foo twice.

I think the purpose of author is that we should not change the value of variables existing in macro's replacement am I right?

No, I don't think this is the purpose.

really I did not understand at all about the Common error. Can you explain it by code?

For example, let's say you did declare the aforementioned max macro. From that point on, so long as you do not #undef that macro, you're going to have problems using anything called max. For instance, this won't compile: std::numeric_limits<int>::max().


推荐阅读