Read Char From File Portability Bugs + Fix | C Programming Example

preview_player
Показать описание
Рекомендации по теме
Комментарии
Автор

The type char is an integer type, like int. The problem is that on most machines it is smaller than int, and so cannot represent all of the values. If a function returns an int value, then unless you know that the value is between CHAR_MIN and CHAR_MAX, you are potentially converting the value to a different value if you force it to char. If a function returns int, then it behooves you to capture its value into a variable of that same type, or else some type which is a guaranteed superset like long.

In the case of fgets, the range of values it returns is a byte value in the range 0 to UCHAR_MAX, or else EOF which is negative. So right off the bat we have a problem. Let's assume bytes are 8 bits, and arithmetic is two's complement. The fgets function therefore returns 257 different values: 256 possible byte values or else EOF. An 8 bit char cannot represent 257 different values, so something has to give. If char is signed, then the byte value 255 will get converted to -1, which may look like a false positive for EOF. If char is unsigned, then none of its values are equal to EOF; the loop will not terminate. Either situation is a bug.

kazkylheku
Автор

yesterday, i was googling this problem with getting a char from user, and i found that you have to use space before %c in scanf, like that scanf(" %c", &ch);, and i know that there are getchar and getch/getche but they didn't help, so now i'm using scanf(" %c", &ch) always

nemoo
Автор

i want to ask if you can explain "detached threads",
your way of explaining really help us

RoockYou
Автор

can u please explain in a video about runtime complexity in C please

ionguzun