EmbLogic's Blog

functions and command line arguments.

Functions :
Functions are easy to use; they allow complicated programs to be parcelled up into small blocks, each of which is easier to write, read, and maintain. We have already encountered the function main and made use of I/O and mathematical routines from the standard libraries. Now let’s look at some other library functions, and how to write and use our own.

Calling a Function:

The call to a function in C simply entails referencing its name with the appropriate arguments. The C compiler checks for compatibility between the arguments in the calling sequence and the definition of the function.

Library functions are generally not available to us in source form. Argument type checking is accomplished through the use of header files (like stdio.h) which contain all the necessary information. For example, as we saw earlier, in order to use the standard mathematical library you must include math.h via the statement

Command-line arguments:

It is standard practice in UNIX for information to be passed from the command line directly into a program through the use of one or more command-line arguments, or switches. Switches are typically used to modify the behavior of a program, or to set the values of some internal parameters. You have already encountered several of these–for example, the “ls” command lists the files in your current directory, but when the switch -l is added, “ls -l” produces a so-called “long” listing instead. Similarly, “ls -l -a” produces a long listing, including “hidden” files, the command “tail -20″ prints out the last 20 lines of a file (instead of the default 10), and so on.

Conceptually, switches behave very much like arguments to functions within C, and they are passed to a C program from the operating system in precisely the same way as arguments are passed between functions. Up to now, the main() statements in our programs have had nothing between the parentheses. However, UNIX actually makes available to the program (whether the programmer chooses to use the information or not) two arguments to main: an array of character strings, conventionally called argv, and an integer, usually called argc, which specifies the number of strings in that array. The full statement of the first line of the program is

main(int argc, char** argv)

(The syntax char** argv declares argv to be a pointer to a pointer to a character, that is, a pointer to a character array (a character string)–in other words, an array of character strings. You could also write this as char* argv[]. Don’t worry too much about the details of the syntax, however–the use of the array will be made clearer below.)

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>