a c programming question
all. I am not sure whether it is appropriate to ask such a 'simple' question here, but actually it's hard for me :[ , and here is the question and a bit of c code:
main()
{
int c, i;
for (i = 0; (c = getchar()) != EOF && c != '\n'; ++i)
printf("%d", i);
if (c == '\n')
printf("%d", i);
}
开发者_JAVA百科
After executing this program, when I input, say, "abc\n", the program will return:
0
1
2
3
I wondered why the result is not
0
1
2
since when c == '\n', there are no statement that increments i by 1. This is what I thought, I must be wrong, would you tell me where I was wrong? Thanks!
The sequence of operations in the for
loop are:
i = 0
(c = getchar()) != EOF && c != '\n' // c is set to 'a'
printf("%d", i) // displays 0
++i // i == 1
(c = getchar()) != EOF && c != '\n' // c is set to 'b'
printf("%d", i) // displays 1
++i // i == 2
(c = getchar()) != EOF && c != '\n' // c is set to 'c'
printf("%d", i) // displays 2
++i // i == 3
(c = getchar()) != EOF && c != '\n' // c is set to '\n'
// the loop exits
So the printf()
that's after the for
loop prints the most recent value for i
, which is 3.
The ++i
gets executed after the c == '\n'
case.
Perhaps this code would help clarify?
int i;
for (i = 0; i <= 3; ++i)
printf("%d\n", i);
At the end of the loop, i will be 4, because of that final increment.
The main problem is with pre increment of index variable i. In stead of pre increment, use post increment i.e. i++ inside the for loop.The reason behind that is due to pre increment. When the condition inside the loop halts, the value stored in i is already 4 when you use pre increment.
main()
{
int c, i;
for (i = 0; (c = getchar()) != EOF && c != '\n'; i++)
printf("%d", i);
if (c == '\n')
printf("%d", i);
}
精彩评论