I am afraid that you are mistaken: in the context of the expression for incrementing the operator for ++i , i++ , i += 1 and i = i + 1 they all have the same effect. In addition, this increment expression is executed after after each iteration before evaluating the condition, but not before the first iteration. Following are the steps to evaluate the for statement:
- evaluates the initialization expression
i = 0 ; - evaluate the condition expression: if it is false, exit the loop.
- evaluate body cycle:
- If
break statement is evaluated, exit the loop - if the
continue statement is evaluated by the branch directly in step 4; - otherwise go to step 4.
- evaluate the expression of the increment
++i ; - go 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 one that did not have a condition, for which str1[i] == '\0' , which is known as the length of the string C in str1 . This is the index where you want to keep the null delimiter in str2 .
Please note that the code can be simplified and made safer as follows:
#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; }
source share