Command-Line Arguments - Differences between C and Java

If you use the command line to execute a program, you can pass information to the program via the command-line arguments. For example, using a Java program called MyJavaProgram, the user might type the following into the command line:

user@mycomputer> java MyJavaProgram 21 blue 

This starts up the main() function of the MyJavaProgram class. A proper Java main() function takes a String array as its argument, usually called args. In this case, the args[0] will be “21”, and args[1] will be “blue”.

To do the same thing in a C program, your main() function should be defined as follows:

int main(int argc, char **argv) { // command-line args 
    //...
}

The variable argc means “argument count”. It will simply hold the number of command-line arguments (including the command to activate the program). The variable argv (“argument values”) is a little more complicated, and we will explain the significance of the ** below. For now, it suffices to think of it as an array of strings holding the command-line arguments. So if the user runs the program a.out by typing:

user@mycomputer> a.out 21 blue 

then argv[0] will be “a.out”, argv[1] will be “21”, and argv[2] will be “blue”. Using this technique, the C program can take needed information directly from the command line.


Licenses and Attributions


Speak Your Mind

-->