Reputation: 129
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
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
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