Page 87 - Programming Microcontrollers in C
P. 87
72 Chapter 2 Advanced C Topics
The above version of strlen() will return the number of char
acters in the string not including the terminating 0. The function
gets() is a standard function that retrieves a character string from
the keyboard. The prototype for this function is contained in stdio.h.
It is interesting to note that the function strlen() can be altered in
several ways to make the function simpler. The index i in the function
can be post-incremented in the argument so that it is not necessary to
have the statement following the while(). This function will be
int strlen(char *p)
{
int i=0;
while(p[i++]!=0);
return i;
}
Because the while() argument is evaluated as a logical state
ment, any value other than 0 will be considered TRUE. Therefore,
int strlen(char *p)
{
int i=0;
while(p[i++]);
return i;
}
provides exactly the same performance. Yet another viewpoint is found
by
int strlen(char* p)
{
int i;
for(i=0;*p++;i++);
return i;
}
Each of the above functions using strlen() show a different
operation involving passing arguments by reference.
Let us examine another use of passing arguments by pointers.