Jack Deed
Jack Deed

Reputation: 129

C FILE pointer, why not just use the FILE type directly?

I know that in C we have to declare a pointer to the FILE type. Why can't we directly just use the FILE type instead of having to use a pointer to the FILE?

FILE *file;
FILE file; // Why can't we use this instead?

Upvotes: 6

Views: 361

Answers (2)

M.M
M.M

Reputation: 141544

C originally didn't have the ability to pass structures by value, this was added in ANSI C89.

FILE wouldn't have worked in K&R C. Since FILE * works just fine, there was no need or benefit to redesign the functions to work with FILE instead of FILE * when ANSI C was being drafted.

As Kerrek SB points out, another benefit of FILE * is that FILE could be a typedef'd struct tag and this leaves the implementation free to implement it in whichever way is best, without breaking any working programs.

Upvotes: 2

Kerrek SB
Kerrek SB

Reputation: 476960

A FILE is a resource. A given file only exists once and cannot move around. This makes a FILE unsuitable for C's value semantics. Whenever you have a resource, you refer to the resource by passing around a pointer to the resource, which is what the C API is doing.

(Moreover, the definition of FILE is private to the implementation and not part of the standard, which is an essential piece of freedom that you want implementers to have.)

Upvotes: 5

Related Questions