Explaining “int main (int argc, const char * argv[])”
In my quest to teach myself C, I’ve started every program with the same basic function “main()”.
For example,
#include <stdio.h>
main()
{
printf(“Hello World”);
}
So I was puzzled when I began using Xcode on the Mac. Xcode begins every new C project with the following as the main function
“int main(int argc, const char * argv[])”
You’re probably wondering what the difference is and so was I. So I turned to Google and found the answer. The parameter argc is the argument count at the time the program is invoked. For example, if your program was called “dan” and you typed “dan one two” into the command line the computer would execute dan.exe after passing “one” and “two” into the program. The value stored in the program for argc would be 3 (including the program name). The parameter argv on the other hand is the actual array of arguments. In our example the array of arguments would be
argv[0] = “dan”
argv[1] = “one”
argv[2] = “two”
It’s pretty common to pass arguments into a program when invoking it. Therefore it makes sense that Xcode adds these parameters to the main function by default. I’m glad I learned that.