0

for (int c = fgetc(file); c != EOF; c = fgetc(file))

Is it

for (int c = fgetc(file); c != EOF)

more than enough? Why do we need to add "c = fgetc(file)"?

It seems redundant to me. Thanks.

1 Answer 1

1

A for statement has three parts, the initialization, the test, and the incrementation. The second c = fgetc(file) is the incrementation. Remember, the initialization, the first call to fgetc, is only executed once. To keep looping, it has to be done in the incrementation step too.

However, I've always had a problem with this usage of a for loop. A for loop is best used for looping a fixed or predictable number of times, such as the value in a var. When looping until a certain condition is found, it's far better to use a while loop.

In this case, here's the specific problem. The for loop will exit when it detects an EOF. BUT, it tests before it increments. This loop will do the last valid read, run the loop, come back and test for EOF. Since the EOF hasn't been triggered yet, it will do one more read (which sets the EOF condition, but the for loop doesn't test for it yet), execute one additional pass through the loop with unpredictable results, and then, will return to the for loop, detect the EOF and end the loop. It has done one extra pass in the loop that it should not do!

If this had been a while loop, it would do the read and then test for EOF as it should, and would avoid the extra pass that the for loop does.

I've been seeing this usage of for loops a lot lately. You need to be careful when doing it, or should avoid this type of usage.

If this answers your question, please click on the check mark to accept. Let's keep up on forum maintenance. ;-)

1
  • Thanks! Can I modify that as below? (As other suggests) -- for (int c; c = fgetc(file); c != EOF) ---- or ---- while ((int c; c = fgetc(file); c != EOF)
    – Nexus
    Commented Oct 31, 2019 at 20:41

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .