I'm afraid you are mistaken: in the context of the increment expression of the for
statement, ++i
, i++
, i += 1
and i = i + 1
all have the same effect. Furthermore, this increment expression is executed once after each iteration, before evaluating the condition, but not before the first iteration. Here are the steps for the for
statement evaluation:
- evaluates the initialization expression
i = 0
;
- evaluate the condition expression: if it is false, exit from the loop.
- evaluate the body of the loop:
- if a
break
statement is evaluated, exit the loop
- if a
continue
statement is evaluated branch directly to step 4 ;
- otherwise, branch to step 4.
- evaluate the increment expression
++i
;
- branch to step 2.
The last statement correctly uses str2[i] = '\0';
. The value of i
at the end of the for
loop is the first that failed the condition, the one for which str1[i] == '\0'
, which is known as the length of the C string in str1
. This is the index at which you want to store the null terminator in str2
.
Note that the code can be simplified and made safer this way:
#include <stdio.h>
int main(void) {
char str1[100], str2[100];
if (scanf("%99s", str1) == 1) {
for (int i = 0; (str2[i] = str1[i]) != '\0'; i++) {
continue;
}
printf("%s\n", str2);
}
return 0;
}