Revision as of 06:15, 23 January 2012 by Rhea (Talk | contribs)


Important information you should know if you come from CS159

In CS159, students are taught that the main function is defined as follows:


(hash)include <stdio.h>

int main()

{

   ... (rest of code here)
   
   return 0;

}

Instead of this, you can put in arguments in the main function:


(hash)include <stdio.h>

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

    ... (rest of code here)
    return 0;

}

Here, int argc is the number of arguments ( argument count ) given when you compile the code using gcc. For example:

$ gcc example1.c

$ ./a.out

Also note "./a.out" is analogous to a.out used in CS159. Also, here int argc has a value of 1, where "./a.out" also counts as a argument. Note that we can have more than 1 argument (like filename, output filename, etc.).

"char *argv[]" is an array containing all the arguments entered by the user (argument value). So therefore, in the above example, "./a.out" is argv[0], and so on. The length of "char *argv[]" is always int argc.

These two arguments can be used to get important information from the user without using the scanf function. This has many applications, especially in this course and later on.

Also, regarding the return value of the main function, it doesn't always have to be 0. It can be any integer. Conventionally, if a program gives out the expected result, the return value is 0, and if something goes wrong, the return value is -1.

-- Kritin Gokharu


Back to ECE264

Alumni Liaison

Prof. Math. Ohio State and Associate Dean
Outstanding Alumnus Purdue Math 2008

Jeff McNeal