Your code uses i in a while loop to check each character. and an if test to check the next character. It then sets a variable to i+1 and returns that variable.
It could simply return i+1.
The if test and redundant variable can be removed.
int i=0;
while(buffer[i])
i++;
return i;
The while loop simply marches along looking for a NULL. If the character in the ith position is not NULL, i is incremented. If it is NULL, the while loop terminates.
Given a string like "cat", i is set to 0. Since c is not NULL, i is set to 1. Since a is not NULL, i is set to 2. Since t is not NULL, i = set to 3. Since the next character is NULL, the while loop terminates, and i (3) is returned.
I'd have to be pedantic and say that function doesn't return the length of a char array, it reurns the length of a C string.
But, as has already been pointed out, what's wrong with strlen?
@ Paul,,
thanks for your reply. I tested to return i+1, but it would not compile.When I loaded i+1 into a variable, it worked.
I also had a similar problem here:
this works:
int deg(float rad){ // Calculation of degrees from radians.
float degVal = rad * 180.00 / 3.1416;
int intVal= int(round(degVal));
return intVal;
}
this didn't:
int deg(float rad){ // Calculation of degrees from radians.
float degVal = rad * 180.00 / 3.1416;
return int(round(degVal));
}
Where is my mistake?
@ Groove
thanks for your comment.
I don't understand the difference between a C char array and a string, as a "string" appears to me just like an array of characters which is NULL terminated. That is why I called it char array.
And, yes, indeed, there's nothing wrong with strlen(), - except that I didn't find it in the reference....
I don't know how int() is implemented. It may be implemented as a macro that doesn't play well with return. The usual way to convert a float to an int is with a cast:
return (int)round(degVal);
For non-programmers, the (int) looks strange. Since the target audience for Arduino is non-programmers, there is a int() "function" that can be used, instead. Although, apparently not everywhere.
[edit]Groove's comments were about the difference between an array length (the number of elements in an array) and the number of valid values in that array. In the case of a string, the number of valid values is defined by the position of an invalid character (the NULL). So, technically, what you are returning is not the length of the array. It is the length of the string in the array.
It seems to me a "'C' style char array" and a "'C' string" are not necessarily the same thing. A "'C' string" has a terminating '0' to indicate its end while a "'C' style char array" doesn't.