getc() vs fgetc() - What are the major differences?

Joe DF picture Joe DF · Aug 28, 2013 · Viewed 48.4k times · Source

Everywhere I see "it is practically identical", or something similar...

From The GNU C Programming Tutorial :

There is another function in the GNU C Library called fgetc. It is identical to getc in most respects, except that getc is usually implemented as a macro function and is highly optimised, so is preferable in most situations. (In situations where you are reading from standard input, getc is about as fast as fgetc, since humans type slowly compared to how fast computers can read their input, but when you are reading from a stream that is not interactively produced by a human, fgetc is probably better.)

What are the other differences? I have heard that they each have a different implementation (and one can be used as a macro) but, what makes them soo different (or different enough) for them to be both in the Standard C library (or specification)?

Answer

mohit picture mohit · Aug 28, 2013

From the Advanced Programming in Unix Environment:

...

The difference between getc and fgetc is that getc can be implemented as a macro, whereas fgetc cannot be implemented as a macro. This means three things:

  • The argument to getc should not be an expression 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 an argument to another function.
  • Calls to fgetc probably take longer than calls to getc, as it usually takes more time to call a function.

...