|
|
|
|
|
|
|
{
int i = 0; // Index variable
while (str[i] != '\0')
// Invariant (prior to test):
// No character in str[0..i-1] is '\0'
i++;
return i;
} |
|
|
|
|
|
|
|
|
The value of i is the correct value for this function to return. If the array being examined is |
|
|
|
|
|
|
|
|
then i equals 2 at loop exit. The string length is therefore 2. |
|
|
|
|
|
|
|
|
The actual parameter to the StrLength function can be a string variable, as in the function call |
|
|
|
|
|
|
|
|
cout << StrLength(myStr); |
|
|
|
|
|
|
|
|
or it can be a string constant: |
|
|
|
|
|
|
|
|
cout << StrLength("Hello"); |
|
|
|
|
|
|
|
|
In the first case, the base address of the myStr array is sent to the function, as we discussed in Chapter 11. In the second case, a base address is also sent to the function-the base address of the unnamed array that the compiler set aside for the string constant. |
|
|
|
|
|
|
|
|
There is one more thing we should say about our StrLength function. A C++ programmer would not actually write this function. The standard library supplies several string-processing functions, one of which is named strlen and does exactly what our StrLength function does. Later in the chapter, we look at strlen and other library functions. |
|
|
|
|
|