In POSIX systems (like Linux and macOS), programs can receive arguments from the command line when they are executed. These arguments can be used to customize the program's behavior. They are accessed through the main
function.
main
Function
The standard signature for the main
function in C/C++ that accepts command-line arguments is:
int main(int argc, char *argv[]);
or equivalently:
int main(int argc, char **argv);
Here's what the parameters mean:
argc
(Argument Count): This integer variable holds the number of command-line arguments, *including* the name of the program itself. So, if you run a program with no arguments other than its name, argc
will be 1.argv
(Argument Vector): This is an array of C-style strings (char*
). Each element of argv
represents a command-line argument.
argv[0]
is always the name of the program as it was invoked.argv[1]
is the first argument.argv[2]
is the second argument, and so on.argv[argc - 1]
is the last argument.argv[argc]
is guaranteed to be NULL
, marking the end of the argument list.
In C#, the Main
method's signature for accepting command-line arguments is typically:
static int Main(string[] args);
or sometimes:
static void Main(string[] args);
Here's what the parameter means:
args
: This is an array of strings. Each element of args
represents a command-line argument.
args[0]
is the first argument.args[1]
is the second argument, and so on.
Note that in C#, the program name itself is *not* included in the
args
array. The array only contains the arguments
provided *after* the program name. The `Main` method in C#
can return an integer value, which is often used as an exit code
for the program.
Let's say you have a program named myprogram
(or myprogram.exe
on Windows). If you compile it and run it from the command line like this:
./myprogram -n 10 output.txt
Then, inside the main
function (C/C++):
argc
will be 4.argv[0]
will be "./myprogram".argv[1]
will be "-n".argv[2]
will be "10".argv[3]
will be "output.txt".argv[4]
will be NULL
.And, inside the `Main` method (C#):
args[0]
will be "-n".args[1]
will be "10".args[2]
will be "output.txt".Command-line arguments are commonly used to provide options, filenames, or other input to a program when it starts. This makes programs more flexible and allows users to control their behavior without recompiling the code.