|
|
The manual page for each function describes how
you should use the function in your program.
As an example, consider the strcmp() routine,
which
compares character strings.
See
string(S)
for more information.
Related functions are described
there as well, but
only the sections relevant to strcmp()
are shown in
``Excerpt from string(S) manual page''.
Excerpt from string(S) manual page
NameThe Description section tells you what the function or macro does. The Syntax section contains the critical information about how you use the function or macro in your program.string: strcat, strdup, strncat, strcmp, strncmp, strcpy, strncpy, strlen, strchr, strrchr, strpbrk, strspn, strcspn, strok - string operations.
Syntax
cc . . . -lc
#include <string.h>
...
int strcmp (s1, s2) char *s1, *s2;
...
Description
...
strcmp compares its arguments and returns an integer less than, equal to, or greater than 0, according as s1 is lexicographically less than, equal to, or greater than s2. strncmp makes the same comparison but looks at most n characters.
...
Note that the line in the Syntax section:
#include <string.h>means that you should include the header file string.h in your program because it contains useful definitions or declarations relating to strcmp(). string.h contains the line:
extern int strcmp(const char , const char );that describes the kinds of arguments expected and returned by strcmp(). This line is called a function prototype. Function prototypes afford a greater degree of argument type checking than old-style function declarations, so you lessen your chance of using the function incorrectly. By including string.h, you assure that the compiler checks calls to strcmp() against the official interface. You can, of course, examine string.h in the standard place for header files on your system, usually the /usr/include directory.
The next thing in the Syntax section is the formal declaration of the function. The formal declaration tells you:
How strcmp() is used in a program
#include <string.h>/ birds must be in alphabetical order / char birds[] = { "albatross", "canary", "cardinal", "ostrich", "penguin" };
/ Return the index of the bird in the array. / / If the bird is not in the array, return -1 /
int is_bird(const char string) { int low, high, midpoint; int cmp_value;
/ use a binary search to find the bird / low = 0; high = sizeof(birds)/sizeof(char ) - 1; while(low <= high) { midpoint = (low + high)/2; cmp_value = strcmp(string, birds[midpoint]); if (cmp_value < 0) high = midpoint - 1; else if (cmp_value > 0) low = midpoint + 1; else / found a match / return midpoint; } return -1; }