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?
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:
$ ./a.out arg1 arg2
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 in argv
(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++
#include <iostream>
int main(int argc, char * argv[]){
int i;
for(i = 0; i < argc; i++){
std::cout << "Argument "<< i << " = " << argv[i] << std::endl;
}
return 0;
}
C
#include <stdio.h>
int main(int argc, char ** argv){
int i;
for(i = 0; i < argc; i++){
printf("Argument %i = %s\n", i, argv[i]);
}
return 0;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With