5.7.6. The Main Function

When the operating system starts your program, it calls a function called main. (Note that the function must have exactly that name. The operating system will not call a function called Main or MAIN.)

Simple main function

You can write main with heading
  int main()

The integer value returned by main is a number between 0 and 255. It is a status value that is returned to the operating system and tells the operating system whether the program was successful. The convention is that a result of 0 indicates that the program succeeded and any other result indicates that the program encountered an error.


Getting the command line

If you want main to take parameters, the heading for main should be

  int main(int argc, char** argv)
Parameter argv is an array of null-terminated strings and argc is its size. The information passed to main by the operating system depends on the command that is used. The command is broken down into pieces, normally by breaking it at spaces (or sequences of spaces and tabs). For example, if you perform command
  jump -r data.txt
then argc is 3 and array argv holds the following strings.
  argv[0] = "jump"
  argv[1] = "-r"
  argv[2] = "data.txt"

If you put quotes around something in a command, it is made into one thing in the argv array. For example, when command

  jump -r -a "some data"
is performed, program jump is passed argc = 4 and
  argv[0] = "jump"
  argv[1] = "-r"
  argv[2] = "-a"
  argv[3] = "some data"