fgetc和getc的区别
The function getchar is defined to beequivalent to getc(stdin). The difference between the first two functions isthat getc can be implemented as a macro, whereas fgetc cannot be implemented asa macro. This means three things.
The argument to getc should not be anexpression with side effects.
Since fgetc is guaranteed to be a function,we can take its address. This allows us to pass the address of fgetc as anargument to another function.
Calls to fgetc probably take longer thancalls to getc, as it usually takes more time to call a function.
区别在于调用getc函数时所用的参数fp不能是有副作用的表达式,而fgetc函数则可以,也就是说,getc可以被当作宏来调用,而fgetc只能作为函数来调用。
因此,调用getc比调用fgetc耗费的时间少。
int getc(FILE *fp)
int fgetc(FILE *fp)
所以fgetc是一个函数
getc是一个宏
一般来说宏产生较大的代码,但是避免了函数调用的堆栈操作,所以速度会比较快。
但是也有例外的情况:
1. 很多RISC处理器(如SUN SPARC)使用寄存器窗口重叠技术,
(http://server.chinabyte.com/404/157904_1.shtml),
在寄存器充足的情况下,根本不需要堆栈操作,fgetc函数比getc宏更快
2. 在多线程的情况下,为了线程同步,getc和fgetc可能是相同的。
有副作用的表达式,指的是表达式执行后,会改变表达式中某些变量的值
最简单的如++i,这个表达式执行后,i的值会改变,这样的表达式是不应该在宏调用里出现的
#define MACRO_SQRT(x) (x)*(x)
int func_sqrt(int x)
{
return x * x;
}
上面是两个计算平方的方法,一个用宏,一个用函数
int i=2;
MACRO_SQRT(++i) 与 func_sqrt(++i)将是不同的~
查了下getc,在stdio.h中有宏定义的版本,而fgetc是函数~
int i=2;
int a,b;
a=MACRO_SQRT(++i); //代码看起来只是让i自加一次,但由于宏的原因,实际可能不止,因而用宏一般不要使用有“副作用”的表达式
cout << "a=" << a<<" i="<< i<< endl;
i=2;
b=func_sqrt(++i);
cout << "b=" << b<<" i="<< i<< endl;