Togeri Togeri -4 years ago 77
C Question

Control flow understanding

I'm having a lot of trouble understanding the following program flow:

#include <stdio.h>
#include <ctype.h>

int main ()
{
FILE *fp;
int index = 0;
char word[45];
int words = 0;

fp = fopen("names.txt","r");
if(fp == NULL)
{
perror("Error in opening file");
return(-1);
}


for (int c = fgetc(fp); c != EOF; c = fgetc(fp))
{
// allow only alphabetical characters and apostrophes
if (isalpha(c) || (c == '\'' && index > 0))
{
// append character to word
word[index] = c;
index++;

// ignore alphabetical strings too long to be words
if (index > 45)
{
// consume remainder of alphabetical string
while ((c = fgetc(fp)) != EOF && isalpha(c));

// prepare for new word
index = 0;
}
}

// ignore words with numbers (like MS Word can)
else if (isdigit(c))
{
// consume remainder of alphanumeric string
while ((c = fgetc(fp)) != EOF && isalnum(c));

// prepare for new word
index = 0;
}

// we must have found a whole word
else if (index > 0)
{
// terminate current word
word[index] = '\0';

// update counter
words++;

//prepare for next word
printf("%s\n", word);
index = 0;
}
//printf("%s\n", word);
}

printf("%s\n", word);

fclose(fp);
return(0);
}


As you can see, it's just a plain program that stores characters from words into an array, back-to-back, from a file called 'names.txt'.

My problem resides in the
else if(index > 0)
condition.
I've run a debugger and, obviously, the program works correctly.

Here's my question:

On the first for-loop iteration,
index
becomes 1. Otherwise, we wouldn't be able to store a whole word in an array.

If so, how is it possible that, when the program flow reaches the
else if (index > 0)
condition, it doesn't set
word[1]
to 0? (Or the subsequent values of
index
).

It just finishes the whole word and, once it has reached the end of the word, then it proceeds to give
word[index]
the value of 0 and proceed to the next word.

I've tried reading the documentation, running half of the program and asking with echo, and running a debugger. As it should be, everything runs perfectly, there's no problem with the code (as far as I know). I'm the problem. I just can't get how it works.

PS: sorry if this might be so trivial for some of you, I'm really starting to learn programming and I find sometimes really hard to understand apparently so simple concepts.

Thank you very much for you time guys.

Answer Source

As soon as something is executed in the if...else block, it moves out of the block. So if it satisfies the first if condition, the else if condition is not even checked. So if index > 0 AND c=\ or c is an alphabet, it runs the if statement, and if even one of these conditions does not hold true, it will move to the else if portions of the block.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download