c - 函数宏问题

标签 c function c-preprocessor

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/

相关文章:

c - __iob_func 在使用 GSL 库时在函数 _gsl_error 中引用

Javascript 继承 : How prototype chain works between native prototypes

javascript - 在插件函数上创建 setTimeout

c - 从函数导出列表

c - 按钮处理(伪代码/c)

r - 曲线错误(): 'expr' did not evaluate to an object of length 'n'

具有 0 或 1 个参数的 C++ 宏

c - 如何使用 ## 运算符通过宏扩展生成字符串或字符常量

c++ - 多个文件包含到单个类冲突

c - XPM 图像内存分配