C Language Command-line arguments

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Extensions
> Step 2: And Like the video. BONUS: You can also share it!

Syntax

  • int main(int argc, char *argv[])

Parameters

ParameterDetails
argcargument count - initialized to the number of space-separated arguments given to the program from the command-line as well as the program name itself.
argvargument vector - initialized to an array of char-pointers (strings) containing the arguments (and the program name) that was given on the command-line.

Remarks

A C program running in a 'hosted environment' (the normal type — as opposed to a 'freestanding environment') must have a main function. It is traditionally defined as:

int main(int argc, char *argv[])

Note that argv can also be, and very often is, defined as char **argv; the behavior is the same. Also, the parameter names can be changed because they're just local variables within the function, but argc and argv are conventional and you should use those names.

For main functions where the code does not use any arguments, use int main(void).

Both parameters are initialized when the program starts:

  • argc is initialized to the number of space-separated arguments given to the program from the command-line as well as the program name itself.
  • argv is an array of char-pointers (strings) containing the arguments (and the program name) that was given on the command-line.
  • some systems expand command-line arguments "in the shell", others do not. On Unix if the user types myprogram *.txt the program will receive a list of text files; on Windows it will receive the string "*.txt".

Note: Before using argv, you might need to check the value of argc. In theory, argc could be 0, and if argc is zero, then there are no arguments and argv[0] (equivalent to argv[argc]) is a null pointer. It would be an unusual system with a hosted environment if you ran into this problem. Similarly, it is possible, though very unusual, for there to be no information about the program name. In that case, argv[0][0] == '\0' — the program name may be empty.

Suppose we start the program like this:

./some_program abba banana mamajam

Then argc is equal to 4, and the command-line arguments:

  • argv[0] points to "./some_program" (the program name) if the program name is available from the host environment. Otherwise an empty string "".
  • argv[1] points to "abba",
  • argv[2] points to "banana",
  • argv[3] points to "mamajam",
  • argv[4] contains the value NULL.

See also What should main() return in C and C++ for complete quotes from the standard.



Got any C Language Question?