Just like other functions, main() can also receive the arguments and return a value.
It is possible to pass some values from the command line to your C programs when they are executed. These values are called command line arguments.
We can execute a program (executable file) from operating system’s command prompt by just typing the program name as shown below
C:\tc\bin\> sum.exe //here “.exe” is optional
(Suppose if our program is “sum.c” then its compiled version will be “sum.exe”)
When a program is run, the operating system loads exe file into memory and invokes the startup function i.e. main(). Here, we can assume the OS is the caller of main() function. Therefore, the arguments can be passed to the main() function by specifying a list of values at the command line as shown below.
C:\tc\bin\> sum 10 20 30
Unlike other functions, the arguments to main() are passed in a different manner. They are passed as string constants. That means, even if we give integer values, they passed as string. In this case, the arguments passed as “sum”, “10”, “20”, “30”.(passed as array of addresses to the main())
But main() receives two arguments, the fist argument is integer, which specifies the count of arguments including file name. The second argument is an array of addresses containing strings. Thus main() function should be defined as
void main(int argc, char *argv)
argc – Number of arguments in the command line including program name
argv[ ] – holds addresses of all string constants that are passed to the program.
The input arguments should be separated by space or tab, but not with comma …etc.