Its pretty easy, command line arguments program can be run in the same way as I talked about with the batch files. In fact, for the previously mentioned batch files to even work, you would need command line arguments supported by your program, else your program would treat
example.exe 10 20
in the same fashion as
example.exe
A simple command line argument - compatible program would look like this:
Code:
#include <stdio.h>
void main(int argc, char *argv[]) { /*Note the arguments for the main() function) */
int a=0, b=0, c=0;
a=argv[0]; b=argv[1];
c=a+b;
printf("\nThe sum is %d", c);
}
When you run the above program, called example.c, compiled into example.exe in the following way
example 10 20
it would output
"The sum is 30"
Run it with the "example 20 30" and it would output "The sum is 50" and so on. There are no error handlers in the above program so it doesnt check if you have entered the correct numbers/types of arguments. Remember that argc holds the count of the number of arguments, while the argv holds the actual arguments themselves. Also, remember that since argv[] is an array, it starts with an index value of 0, so argv[0] is the first argument.
When it comes to varargs, well the best example of a function that supports varargs is printf() as you can supply any number of arguments to it and still have it decode and work accordingly. Any function can be made to accept varargs with the ellipsis operator, consisting of the three dots (...) Consider this example:
Code:
#include <stdio.h>
#include <stdarg.h>
void str_printer(const char *start, ...) {
va_list arglist;
int i; char *s;
va_start(arglist, start);
while(s) {
s=va_arg(arglist, char*);
i=va_arg(arglist, int);
if(s)
printf("%s %d\n", s, i);
}
va_end(va_list);
}
void main() {
str_printer("Run1", "Argument1", "Argument2");
str_printer("Run2", "Argument1a", "Argument2a", "Argument3", "Argument4", "AAARGGGH!");
}
When you run this program the output would be:
Code:
Run1 Argument1 Argument2
Run2 Argument1a Argument2a Argument3 Argument4 AAARGGGH!
The parameters are not known to the function until runtime, so it uses the macros from stdarg.h to access them. The program defines a variable arglist of type va_list, which is defined in stdarg.h as an array for obtaining the arguments that come in place of the eliipsis ...
The macro va_start initializes the va_list variable (arglist, which is the first parameter for the macro) and the second parameter is the name of the first parameter accepted by our function str_printer, which is start.
The macro va_arg actually extracts the arguments. So, when its run with s=va_arg(arglist, char*); it knows to expect an argument of type char* and the next va_arg statement is told to expect an int and so on and so forth. The macro va_end cleans it all up and releases memory. Hope this would have explained it a bit.