5D. Programs and the Main Function


Main

A C++ program is a collection of functions, exactly one of which is called main. The program starts by running main, and stops when main returns. All of the other functions constitute a toolbox for accomplishing the desired task.

For now, the heading for main should be

  int main()
That is different from Java. This main function does not take any parameters and it returns an integer, which is a status value telling whether the program was able to complete its job without errors. A status value of 0 indicates that all went well. Any other status value indicates that there was an error. (The status value should be a number from −128 to 127. Typically, only 0 and 1 are used.) If you are sure that your program will work, just return 0.
  int main()
  {
    
    return 0;
  }
Here is a complete program that just writes Hello.
  #include <cstdio>
  using namespace std;

  int main()
  {
    printf("Hello\n");
    return 0;
  }

Later, we will see a more general version of main that takes some parameters, but the simple parameterless form will do for now.


Summary

Every program must have exactly one function called main. For now, we will use heading

  int main()
The value returned by main is passed back to the operating system. A returned value of 0 indicates that the program did its job. Any other returned value indicates that something prevented the program from completing its job.


Exercises

  1. Write a complete program that reads a real number from the user (after a prompt) and writes the square root of that real number. Answer