The symbolic constant EOF
is an integer constant, of type int
. It's (usually) defined as a macro as -1
.
The problem is that the value -1
as an (32-bit) int
has the value 0xffffffff
and as a (8-bit) char
the same value would be 0xff
. Those two values are not equal. Which in turn means that your loop condition will never be false, leading to an infinite loop.
The solution to this problem is that all standard functions that reads characters returns them as an int
. Which means your variable character
needs to be of that type too.
Important note: It's a compiler implementation detail if plain char
is a signed or an unsigned type. If it is signed then a comparison to an int
would lead to sign extension when the char
value is promoted in the comparison. That means a signed char
with the value 0xff
would be extended to the int
value 0xffffffff
. That means if char
is signed then the comparison would work.
This means that your compile have char
as unsigned char
. So the unsigned char
value 0xff
after promotion to int
will be 0x000000ff
.
As for why the value -1
becomes 0xffffffff
is because of how negative numbers are usually represented on computers, with something called two's complement.
You also have another couple of flaws in your code.
The first is that since the loop is infinite you will go way out of bounds of the string
array, leading to undefined behavior (and a possible crash sooner or later). The solution to this is to add a condition to make sure that index
never reaches 100
(in the specific case of your array, should really be passed as an argument).
The second problem is that if you intend to use the string
array as an actual string, you need to terminate it. Strings in C are actually called null terminated strings. That terminator is the character '\0'
(equal to integer 0
), and need to be put at the end of every string you want to pass to a standard function handling such strings. Having this terminator means that an array of 100
characters only can have 99 characters in it, to be able to fit the terminator. This have implications to the solution to the above problem. As for how to add the terminator, simply do string[index] = '\0';
after the loop (if index
is within bounds of course).