(Information for new students)
 
(Removing all content from page)
Line 1: Line 1:
'''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 ( '''[[arg]]'''ument  '''[[c]]'''ount ) 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 ('''[[arg]]'''ument '''[[v]]'''alue). 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.
 

Revision as of 20:12, 26 April 2011

Alumni Liaison

EISL lab graduate

Mu Qiao