ProgrammingVery hard
A character loop reads bytes with char c = getchar() and tests while (c != EOF). Why can this loop be wrong?
- A. char may be unsigned, so EOF (-1) can never be stored, or a 0xFF byte equals EOF when char is signed
- B. getchar is slow, so the loop is too slow
- C. EOF is 0, so the loop stops at the first zero byte
- D. The loop never terminates because c is a pointer
Correct answer: A. char may be unsigned, so EOF (-1) can never be stored, or a 0xFF byte equals EOF when char is signed
EOF is a negative int, and storing it in a plain char is not reliable. The result of getchar must be stored in an int.
More C Programming questions
- To count occurrences of values up to 10^6 in O(n), which code is correct and fast enough?
- A recursive depth-first search could recurse 10^6 levels deep on a path-shaped graph. Which approach is correct and safe?
- A string of up to 10^6 characters is read with fgets. Which buffer declaration is correct?
- A loop walks a string with for (i = 0; i < strlen(s); i++) on a string of length 10^6. What is the total cost?
- A binary search on the answer in [1, 10^18] computes mid = (lo + hi) / 2 with long long. Is this safe?
- A sum of n = 10^5 terms is stored in a double. Is this a safe choice for exact integer sums up to 10^14?