[英]How can “an expression with side effects” be passed to getc?
"Advanced Programming in the UNIX Environment, 3rd Edition", page 151:
第151页,“ UNIX环境中的高级编程,第3版”:
The difference between
getc
andfgetc
is thatgetc
can be implemented as a macro, whereasfgetc
cannot be implemented as a macro.之间的差
getc
和fgetc
是getc
可以被实现为一个宏,而fgetc
不能作为宏来实现。 This means three things:这意味着三件事:
- The argument to
getc
should not be an expression with side effects .getc
的参数不应是带有副作用的表达式 。- Since
fgetc
is guaranteed to be a function, we can take its address.由于
fgetc
被保证是一个函数,因此我们可以获取其地址。 This allows us to pass the address offgetc
as an argument to another function.这使我们可以将
fgetc
的地址作为参数传递给另一个函数。- Calls to
fgetc
probably take longer than calls togetc
, as it usually takes more time to call a function.调用
fgetc
可能比调用getc
花费更长的时间,因为调用函数通常花费更多时间。
What "expression with side effects" can occur for the function signatures with stream pointer as a parameter? 以流指针作为参数的函数签名会发生什么“副作用的表达” ?
#include<stdio.h>
int getc(FILE* stream);
int fgetc(FILE* stream);
There are probably hundreds of ways to pass an expression with side effects, but a "credible" one would be something like: 传递带有副作用的表达式的方法可能有数百种,但是“可信的”表达式将类似于:
FILE *files[NUM_FILES];
...
int rc = getc(files[counter++]);
If getc
is implemented poorly as a macro, the expression files[counter++]
could be evaluated more than once, leading to unexpected behavior. 如果
getc
不能很好地实现为宏,则表达式files[counter++]
可能会被多次评估,从而导致意外行为。
As an example, don't write 例如,不要写
FILE* foo() { puts( "Bah!\n" ); return stdout; }
void advance() { getc( foo() ); }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.