Revision as of 20:09, 26 April 2011 by Kgokharu (Talk | contribs)

(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)

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.

Alumni Liaison

Correspondence Chess Grandmaster and Purdue Alumni

Prof. Dan Fleetwood