We know main() is the function that indicates the starting point of our C program. While writing our C program, we are just writing the definition of main() function. Later main() function can be invoked by a system call of operating system of your computer when the user trying to run your program in some way.
Since main() is a function it can also return or not return a value to its caller(o/s). Returning integer value 0 means communicating to o/s that your program has successfully completed its job and the o/s can deallocate any resources allocated to your program. Returning value 1 means there might have some error happened in the execution of the program.
Now, coming to the topic of our discussion arguments to main() function. Till now, we have defined main() function without arguments.
Arguments are the values that were specified in the function definition for which values to be supplied by the caller of the function at the time of invocation. We already knew that o/s make a call to main() function, we have to pass arguments to main() function(if it was defined like that) through some o/s interface. Windows is our mostly used operating system works in Graphical User Interface. But we can also work with windows user command mode(which its earlier form Ms-DOS).
If you want to define main() function so that it can accept arguments, then we can pass values to those arguments in two ways:
1. through command line (shell prompt) of o/s
2. through respective option of your IDE
In Code blocks IDE, we can pass command line arguments through Project menuProgram arguments.
Syntax for passing values to arguments of main() function through command mode :
cmdPrompt:\>programName arg1 arg2
In the above command programname is also considered as one of arguments to the main function.
//Example code1
#include <stdio.h>
int main(int argc,char *argv[])
{
if(argc==3)
{
printf(“sum of given numbers is %d”,(int)argv[1]+(int)argv[2]);
}
else
{
printf(“No arguments passed except program name”);
}
}
argc in the above program is the variable that stores the number of arguments supplied to main() function
argv[] is a pointer array that holds the values passed to main() function
//example code2
#include<stdio.h>
int main(int argc,char* argv[])
{
int counter;
printf(“Program Name Is: %s”,argv[0]);
if(argc==1)
printf(“\nYou have not passed any arguments except program Name”);
if(argc>=2)
{
printf(“\nTotal Arguments Passed: %d”,argc);
printf(“\nYou have passed the following arguments…:”);
for(counter=0;counter<argc;counter++)
printf(“\nargv[%d]: %s”,counter,argv[counter]);
}
return 0;
}