Reputation: 498
Suppose I have a string "str". My for loop is as follows:
for(i=0;i<strlen(str);i++){
//do stuff
}
question: When the condition is checked ,i < strlen(str), is the strlen(str) part calculated each time the loop runs ? Or it gets stored and is computed for the first time only?
Upvotes: 0
Views: 2339
Reputation: 235984
The condition expression in a loop will get evaluated at each and every iteration - it has to be that way until (ideally) the expression becomes false. So yes: strlen(str)
will be calculated over and over again. If the string doesn't change at all, it'll be better if you store its length in a local variable.
int n = strlen(str);
for (i=0; i<n; i++) {
// do stuff
}
This will also work:
for (i=0; str[i] != '\0'; i++) {
// do stuff
}
Upvotes: 5