Arguments to main() in C – A Brief Guide

In the previous tutorial on variable types, we declared main() without any arguments, and indeed, without any return type. However, this declaration style takes advantage of certain implicit declarations in C. Just as we have left the auto declaration off our variables, with the compiler implicitly treating them like auto variables, so we have let the compiler implicitly declare a return type for main(). However, since the introduction of the ISO standard in C back in 1990, this style of declaration has been considered to be mildly bad practice. In fact, a proper main() declaration with no arguments looks like this:

int main(void)
{
    ...
}

and returns a value of 0 if the program exits successfully; non-zero if there is an error. This tends to be useful for debugging purposes; knowing the return value of your programs can help identify where errors are resulting from.

However, what we’re really interested in at this point are the arguments that main() may be given. main() typically takes two arguments, an integer value named argc (for argument count), which contains the number of command-line arguments that have been taken in, and a pointer to an array of character strings named argv[] (for argument vector), which contains the contents of the individual arguments.

While arguments to main are fairly uncommon in GUI systems, they still find their uses, such as arguments made to open a specific configuration file when opening, or an argument made to a computer game not to display the splash screen when it is starting up. In a command-line system, like the Unix systems where C was born and gestated, they are particularly important for giving the user control over the way they wish the application to be used.

One of the simplest programs to use command-line arguments is echo. In its simplest manifestation, echo simply takes its arguments (apart from the name of the program) and prints them to the standard output with a space between each of the arguments. This simple application, as demonstrated in The C Programming Language (Brian Kernighan and Dennis Ritchie, 2nd Edition, 1988) can be demonstrated here:

#include <stdio.h>

/* echo command-line arguments */
int main(int argc, char *argv[])
{
    int i;
    for (i = 1; i < argc; i++)
        printf("%s%s", argv[i], (i < argc-1) ? " " : "");
    printf("\n");
    return 0;
}

The invocation of this application on the command line as such: “echo hello, world” will print simply, “hello, world”. Given a set of arguments, argc is equal to the number of arguments, which in this case is three. argv[] will contain the strings for each of these arguments; argv[0] will contain “echo“, argv[1] will contain “hello,” and argv[2] will contain “world“. Given these arguments, there is a printf() statement embedded within a for loop which begins at 1 – thus skipping argv[0], which contains the name of the program.

The printf() statement prints two strings, one equal to the value of argv[i] and the other depending on the conditional operator, which finds out if i is less to argc-1. In the case that i is less than argc-1, argc-1 being a value that would point to the last argument in the argv[] array, it prints a space; otherwise, if i is equal to argc-1, it prints out a null string.

There is some potential for confusion with the offset of 1 between argc and the last explicit argument of argv[]. In fact, argv[argc] is defined as a null string, which will make more sense when we cover strings, but until then, all of the useful arguments in argv[] are contained in the array indices from 0 to argc-1.

The echo command may seem a bit trivial, but it has actual applications in a Unix or Unix-like system, particularly when it comes to reporting things in shell scripts. However, a lot of the uses of command-line arguments come courtesy of the idea of setting “flags” for the program. In a Unix system, flags are usually denoted by the minus sign, “-” at the start of the command-line argument. In order to do this adequately, we must include a header file with a function which can be used to compare strings. We can illustrate a use of a flag by modifying our echo command to have a command-line flag argument which allows the user to choose whether they want echo to print a new line or not.

#include <stdio.h>
#include <string.h>

/* echo command-line arguments, allowing newline flag */
int main(int argc, char *argv[])
{
    int i;
    int newline = 0;
    for (i = 1; i < argc; i++) {
        /* Compares two functions, returns 0 if both match */
        if (strcmp(argv[i], "-n") == 0) {
            newline = 1;
        } else {
            printf("%s%s", argv[i], (i < argc-1) ? " " : "");
        }
    }

    if (newline == 1)
        printf("\n");
    return 0;
}

 

 

In the case that “-n” is one of the arguments to main, the newline flag is set, which is checked near the end of the program. All other arguments are echoed to standard output. The strcmp() function takes two string arguments and compares them. If both match, strcmp() returns 0; otherwise, it returns a non-zero value which depends on whether the value of the first string is judged to be greater or less than the second string. This function will be discussed, as with the null string, when we cover strings more completely.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: