That code would return 0 and then exit the function. None of the characters would have been counted, nor would i even be increment. That's why I added a null-statement to the for loop and move i out of the scope.
I see what you have done (and I see about the scope), although I would say that if you are going to use a null statement, then do it like this with the comment, so that everyone can see that you have done it on purpose:
1 2 3 4 5 6 7
int myStrLen(constchar str[])
{
int i = 0;
for(int i = 0; str[i] != '\0'; i++)
; // null statement
return i;
}
Otherwise people might easily think it as an error.
I came up with this:
1 2 3 4
int i;
for( i = 0; str[i] != '\0'; /*no increment*/) {
i++;}
return i;
One can now see why K&R had a while statement. While loops are better if the limit is not a known value.
Any way we have now had 2 days of discussion about the strlen function !!! Given it a thorough bashing I think.
As I said, while loops are better if the end condition or limit is not a known value. For example with strings or files, the length isn't known, so use a while loop. That is what Kernighan & Ritchie (K&R the inventors of the C Language) have done. You can see how the while is easier to understand in the strlen example. The for loop has null statements or missing increment expression. The only thing about the K&R example is they didn't initialise the counter to zero because it is an automatic variable - meaning that it is automatically initialised to zero. However, common practice these days is to initialise nearly everything regardless. Lack of initialisation is one of the most common errors, especially for newbies.