I am reading the function on page 29 from “C programming” by K&R.
In this example:
int getline(char s[], int lim) {
int c, i;
for (i = 0; i < lim - 1 && (c = getchar()) != EOF && c != 'n'; ++i) {
s[i] = c;
}
if (c == 'n') {
s[i] = c;
++i;
}
s[i] = '';
return i;
}
Inside the if (c == 'n') { ... }
block, I don’t understand how the statement s[i] = c;
can work at that point. This code is outside the for
loop that was assigning i
, so where did the value for i
come from?
wantice is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
10
Your confusion seems to be around how a for-loop’s initialization routine works. A for-loop has 3 components in the initial parenthesis:
- An initialization statement
- A conditional expression
- A post-iteration statement
The initialization statement always runs once before the conditional expression is evaluated.
If the conditional expression resolves to true
, the loop iterates once, performs the post-iteration statement, and then re-evaluates the conditional expression. This repeats until the condition resolves to false
or a break
statement (or return
) is encountered.
Note that each for-loop can be converted into an equivalent while-loop, and viewing this code as a while-loop may help clear up some of your confusion. Here is equivalent code using a while(true)
construct to help illustrate the 3 parts of the for-loop that I mentioned.
int getline(char s[], int lim) {
int c, i;
// START: equivalent while-loop
// An initialization statement
i = 0;
while(true) {
// A conditional expression
if (lim - 1 && (c = getchar()) != EOF && c != 'n') {
// The condition is satisfied, run the loop body
s[i] = c;
// A post iteration statement
++i;
} else {
// The condition is no longer satisfied, exit the loop
break;
}
}
// END: equivalent while-loop
if (c == 'n') {
s[i] = c;
++i;
}
s[i] = '';
return i;
}
Viewing the code above should help you see that int i
is indeed assigned a value before it is referenced later in the function.