It is discussed in another thread that reading a file with the following code can result in an infinite loop because EOF is an integer outside the range of char and the while condition therefore cannot become true:
FILE* f; char c; std::string s; f = fopen("/some/file", "r") while ((c = getc(f)) != EOF) s += c; Actually, I have observed that this results in an infinite loop under Linux on Raspberyy Pi, but works fine under Linux on a different hardware.
Why does it work at all?
The only explanation that comes to my mind is that the return value of the assingment statement (c = getc(f)) is not well-defined and returns the left value (a char in this case) on some platforms and the right value (an int in this case) on other platforms.
Can someone shed light on this behaviour?
CHAR_BITis 8 ... YOU ALWAYS LOSE A CHARACTER ... there are 256 different characters "on the keyboard" (more probably in a file);getc()returns aintvalue from the set{<some negative value>, 0, 1, 2, ..., 255}(257 elements). There is absolutely no way to put 257 distinct values inside a 8-bitchar. Using acharfor the intermediate value, you are always, no matter the implementation (with 8-bit signed or unsigned char), either losingEOFor some other character (possibly'\xFF'or signed equivalent).%sa null pointer on some systems and not on others? Answer: Just don't. No reason to speculate on what happens when you do things wrong. Just do it correct from the startEOFis not achar, and didn't ask why that's the case.