I was messing around with projects in C/C++ and I noticed this:
C++
#include <iostream.h>
int main (int argc, const char * argv[]) {
// insert code here...
cout << "Hello, World!\n";
return 0;
}
and
C
#include <stdio.h>
int main (int argc, const char * argv[]) {
// insert code here...
printf("Hello, World!\n");
return 0;
}
So I've always sort of wondered about this, what exactly do those default arguments do in C/C++ under int main? I know that the application will still compile without them, but what purpose do they serve?
Those are for command-line arguments.
argc
is the number of arguments, and the arguments are stored as an array of null-terminated strings (argv
). Normally, a program with no command-line arguments passed in will still have one stored inargv
; namely, the name used to execute the program (which won't always be there, depending on how the program is executed, but I can't remember what the circumstances are for that).They hold the arguments passed to the program on the command line. For example, if I have program
a.out
and I invoke it thusly:The contents of
argv
will be an array of strings containing"a.out"
- The executable's file name is always the first element"arg1"
- The other arguments"arg2"
- that I passedargc
holds the number of elements inargv
(as in C you need another variable to know how many elements there are in an array, when passed to a function).You can try it yourself with this simple program:
C++
C
argc and argv are how command line arguments are passed to main() in C and C++.
argc will be the number of strings pointed to by argv, this will usually be one more than the number of arguments you pass from terminal, as usually the first is the name of the program.
If you want to accept arguments through commandline ,then you need to use the arguments in the main function .argc is the argument count and array of charecter pointers list the arguments. refer this link http://www.cprogramming.com/tutorial/c/lesson14.html