top of page

Command-Line Arguments in C

Introduction


If you're familiar with C, you may know that the scanf() function helps gather user input through the terminal. Another such way is through command-line arguments.


The difference?


The main difference is that scanf() collects input during run time, while command-line arguments are gathered during load time. The two can be interchangeable, but it's just handy to know of a second way to collect user input.

Argument Count and Argument Vector


Previously, your main() function would have looked like this:

int main(void)
{
	...
}

With the addition of command-line arguments, main() changes slightly:

int main(int argc, char *argv[])
{
	...
}

Instead of receiving void or no arguments, main() now takes two cryptic-looking variables: an integer argc and a string array argv (where char * can be treated the same as a string).


  • argc stands for argument count and provides the number of arguments the user typed


  • argv[] stands for argument vector and stores the values the user typed as strings

    • the first element is stored at argv[0]

    • the last element is stored at argv[argc - 1]


It's important to note that because argv[] stores only strings, any user-inputted numbers would have to be converted manually through functions like atoi() (from stdlib.h) in order to perform mathematical operations on them.


Let's take a look at a simple programming using command-line arguments:

Here, a loop runs from 0 to argc-1, accessing all elements within argv. Keep in mind that the first argument in the array (at index 0) is literally the first word you typed, in this case "./program."


Final Thoughts


Hopefully after reading this you're better-equipped at gathering user-input from the get-go. Thanks for reading!

Comments


bottom of page