The function getchar is defined to be equivalent to GETC (stdin ). the difference between the first two functions is that GETC can be implemented as a macro, whereas fgetc cannot be implemented as a macro. this means three things.
1. The argument to GETC shocould not be an expression with side effects.
2. Since fgetc is guaranteed to be a function, we can take its address. This allows us to pass the address of fgetc as an argument to another function.
3. callto fgetc probably take longer than callto GETC, as it usually takes more time to call a function.
Both are used to get a character from stream. The difference is that the parameter stream used to call the GETC function cannot be an expression with side effects (explained later), while the fgetc function can, that is, GETC can be called as a macro, while fgetc can only be called as a function.
Generally, macro calls consume less time than function calls.
- Int fgetc (File * stream );
- Int GETC (File * stream );
Therefore, fgetc is a function.
GETC is a macro.
Generally, macros generate large code, but function call stack operations are avoided, so the speed is faster.
The relevant information also shows that there are exceptions:
1. A lot of server-level CPUs (such as sun or four computers) use the register window Overlap Technology,
When the registers are sufficient, no stack operation is required. The fgetc function is faster than the GETC macro.
2. In the case of multiple threads, GETC and fgetc may be the same for thread synchronization.
An expression with side effects indicates that the value of some variables in the expression is changed after the expression is executed.
The simplest one is ++ I. After this expression is executed, the value of I changes. Such an expression should not appear in macro calls.
- # Define macro_sqrt (x) * (X)
- Int func_sqrt (int x)
- Return x * X;
The above are two square calculation methods. One is macro and the other is function.
Int I = 2;
Macro_sqrt (++ I) and func_sqrt (++ I) will be different ~
- Int A, B;
- /* The following code is normal */
- Int I = 2;
- A = func_sqrt (++ I );
- Printf ("A = % d, I = % d/N", A, I );
- /* The following code is abnormal.
- * The Code only seems to allow I to be automatically added once. However, due to macro reasons, there may be more than one actual code. Therefore, do not use a macro expression with "Side effects ".
- * The Macro will replace all X with x * X. If it is put into ++ I, the compiler will replace all X with ++ I during preprocessing.
- * ++ I appears in the code? How many times does it add itself? This is obviously different from what we want. Check the code.
- I = 2;
- B = macro_sqrt (++ I );
- Printf ("A = % d, I = % d/N", B, I );
Conclusion: The biggest difference between fgetc and GETC is that the former is a function, while the latter is a macro. GETC is implemented by fgetc through a macro. When calling this function, note that the parameter stream cannot be an expression with side effects.