When writing code in C, is it good style to use -1
and EOF
interchangeably? Does the standard guarantee that EOF
is -1
? Or is the value implementation defined?
For example, if a function returns EOF
in certain cases, is it good style to test if the function has returned -1
?
If a function returns -1
in certain cases, is it good style to test if the function has returned EOF
?
No, EOF
most certainly is not guaranteed to be -1
.
It's a macro, defined in <stdio.h>
,
which expands to an integer constant expression, with type
int
and a negative value, that is returned by several functions to indicate end-of-file, that is, no more input from a stream
(quoting from section 7.21.1 of the ISO C standard).
I've never seen an implementation where EOF
has a value other than -1
-- but then I haven't bothered to check.
Using EOF
rather than a literal -1
avoids having your code break on an implementation that chooses a different negative value, but far more importantly it's clear to the reader. If I see -1
in your code, I won't be sure why you chose that particular value. If I see EOF
, I know exactly what you meant. (This would apply even if the standard required EOF
to have the value -1
.)
As for "magic numbers" in general, there are some times when they're unavoidable. An example from the comments: the getopt
function is documented to return -1
in certain circumstances, so you should compare its result to -1
, not to EOF
. Avoid magic numbers when you can, but if the documentation uses them, you're pretty much stuck with them.