C++ Tutorial main function

This C++ Tutorial deals with the main function which is the entry point of any C++ program. A C++ program begins execution at the function main. When a C++ program is compiled and run, the code first executed is the code within the function titled main.

Functions – C++ Tutorial:

Before knowing about main itself though, it is better to know a little about functions. Here?s a sample function:

//Sample code illustrating a function - C++ Tutorial main
int GetMyDogsAge()
return 5;

In the above:

  • int is the return type of the function.
  • GetMyDogsAge is the name of the function.
  • The empty parenthesis specify that the function takes no arguments.
  • The actual executable code for the function goes between the two curly braces – this is called the function?s body.
  • return 5; is what?s called a return statement. When a return statement is reached in a function, the function?s execution ends and it gives a value back to its caller. Every statement in a C++ program ends with ; , a semi-colon.

It’s possible to have a function that does not have a return value, in which case the return type is void :

void DummyFunction()

Note how the return keyword has nothing after it, as DummyFunction doesn?t return a value. In fact you can even omit the return statement:

void DummyFunction()

When a function doesn’t contain a return statement, the function simply ends when all of its body of executable code has been executed and there?s no more statements left to execute, just before the last curly brace.

According to the C++ Standard, the function main must have return type int . An int holds an integer number which may have a positive or a negative value.

You may find it odd that main must have return type int . Why can?t it just be void ? Long story short: because the Standard says so. But… main is a very special function: even though it?s return type is not void , the return statement can be still omitted.

main Function – C++ Tutorial:

Here?s some rules exclusive to main, rules which a typical function is not bound to.

  • The return type of main must be int
  • main may not be called from inside the program, only the system may call the main function.
  • main may not be declared inline nor static

The C++ Standard specifies that a C++ program need not necessarily define a function main . It is exact wording is “It is implementation-defined whether a program in a freestanding environment is required to define a main function.”.

But any normal C++ executable program will need a main function for our purpose. The following is a minimalistic C++ program:

int main() {}

If this were any other function, there would be a compile error.

If a function has a return type, it must return a value, and as such it must contain a return statement.

This is a brief explanation of how a C++ program can be written with just the main function!