How to Use the Main Function in C++

The main function is the entry point for any C++ program and is generally the first code that is executed when the program is run. However, global objects with constructors may execute user-written functions before main is executed. The following steps explain how to declare a main function in C++.

Instructions

    • 1

      Learn the valid function prototypes for the main function. It must consist of one of the following:

      int main();
      int main(void);
      int main(int argc, *argv[]);

    • 2

      Follow the word main with a pair of parentheses, even when there are no arguments. This distinguishes a function declaration from other types of expressions.

    • 3

      Enclose the body of the main function with braces ({}). These braces will contain the code that main will perform when it is executed.

    • 4

      Examine the third prototype given in Step 1. The argument argc provides the number of command-line arguments and argv lists their values. Some platform-dependent implementations may also provide a third argument for the program's environment.

    • 5

      Look at the following program as a use of the main function:

      #include
      int main ()
      {
      cout << "Hello World!";
      return 0;
      }

      This "hello world" program is one of the simplest examples of a C++ program and traditionally the first one encountered by the C++ student. All programs must have a main function.

    • 6

      Observe that other functions may be defined before main is declared. However, the declaration of main marks the beginning of the program regardless of its physical location within the source code.

Related Searches:

Resources

Comments

You May Also Like

Related Ads

Featured