The C specification says that int
must be able to hold values from -32767 to 32767 at a minimum. Any platform with a smaller int
is nonstandard.
The C specification also says that EOF
is a negative int
constant and that fgetc
returns "an unsigned char
converted to an int
" in the event of a successful read. Since unsigned char
can't have a negative value, the value of EOF
can be distinguished from anything read from the stream.*
*See below for a loophole case in which this fails to hold.
Relevant standard text (from C99):
§5.2.4.2.1 Sizes of integer types <limits.h>
:
[The] implementation-defined values shall be equal or greater in magnitude (absolute value) to those shown, with the same sign.
[...]
- minimum value for an object of type
int
INT_MIN
-32767
- maximum value for an object of type
int
INT_MAX
+32767
§7.19.1 <stdio.h>
- Introduction
EOF
... 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
§7.19.7.1 The fgets
function
If the end-of-file indicator for the input stream pointed to by stream
is not set and a next character is present, the fgetc
function obtains that character as an unsigned char
converted to an int
and advances the associated file position indicator for the stream (if defined)
If UCHAR_MAX
≤ INT_MAX
, there is no problem: all unsigned char
values will be converted to non-negative integers, so they will be distinct from EOF.
Now, there is a funny sort of loophole here: if a system has UCHAR_MAX
> INT_MAX
, then a system is legally allowed to convert values greater than INT_MAX
to negative integers (per §6.3.1.3, the result of converting a value to a signed type that cannot represent that value is implementation defined), making it possible for a character read from a stream to be converted to EOF.
Systems with CHAR_BIT > 8
do exist (e.g. the TI C4x DSP, which apparently uses 32-bit bytes), although I'm not sure if they are broken with respect to EOF and stream functions.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…