Guides:C/C Crash Course/More on main()

From CoderGuide

Jump to: navigation, search

Back to TOC

More on main()

As we mentioned, main() is the first function that is run when your program starts. But there is a little more to this function that we haven't mentioned. This function allows us to interface, in a small part, with the operating system.

Like functions, programs return a value as well. This is why you must always declare main() as returning an integer value. Also, like functions, programs can accept parameters.

Return codes, and program termination

The normal return code for a program is 0, any non-zero value (commonly -1) usually indicates some kind of abnormal program termination or failure. It can also be used to provide a shell with extra information about it's termination. The Unix test program returns a value based on if a logical test was true or false, for example.

You can terminate a program by, either coming to the end of main() or having main() come to a return statement during execution. Another way you can terminate your program is by calling the exit() function. It takes one parameter: the exit code. Any function can call it.

Using parameters

We can accept parameters if we add some parameters to main() like so (the order of these parameters is critical):

int main(int argc, char *argv[]){
        /*stuff*/
}

argc stores the number of parameters passed to the program, and argv stores those parameters. As you can see from the definition. There is only one other way you can write function main() if you want to accept parameters:

int main(int argc,char **argv){
}


Both methods mean essentially the same thing, so use whichever one you like. I prefer the second method myself. The names you use for the variables are not important, you can all them anything you like, but it is tradition to use these names for the. You could just as easily change argc and argv to ac/av, or whatever you like, but these are the traditional, and highly recommended, names. It'll make your code more readable by other programmers if you use the traditional labels. What is important is that the first parameter is an integer, and the second is an array of character pointers.

The very first element of argv is not command line a parameter as we would normally think of it, it is the name that was used to run the program. argc value is always at least 1 when executed from a shell (if a system doesn't have a shell, or was executed in some unusual fashion, then argc could be zero), because the the program name counts as a parameter. Here is an example example:

/****
 main.c -- a program to demonstrate receiving command line parameters
***/
#include <stdio.h>
 
int main(int argc, char **argv){
        int i;
 
        printf("You called %s with %d parameters, and they are:\n",
           argv[0],argc-1);
 
        for(i=1;i<argc;i++){
                printf("\"%s\"\n",argv[i]);
 
        }
 
        return 0;
}
Personal tools