The Practice of Programming 一书说:
One of the most serious problems with function macros is that a parameter that appears more than once in the definition might be evaluated more than once; if the argument in the call includes an expression with side effects, the result is a subtle bug. This code attempts to implement one of the character tests from :
#define isupper(c) ((c) >= 'A' && (c) <= 'Z')
Note that the parameter c occurs twice in the body of the macro. If i supper is called in a context like this,
while (isupper(c = getchar()))
then each time an input character is greater than or equal to A, it will be discarded and another character read to be tested against Z.
我不明白如何丢弃大于 >= A 的字符。
最佳答案
由于宏定义在实际编译之前以文本形式扩展到程序中,
isupper(c = getchar())
会扩展到
((c = getchar()) >= 'A' && (c = getchar()) <= 'Z')
根据 &&
的短路规则调用 getchar
两次当且仅当它第一次返回 >= 'A'
并赋值 c
第二次调用返回的值。
关于c - 函数宏问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7960852/