C++ Tutorials


Main Function

Tutorials > C++ > Main Function

View Full Source


This tutorial will show you how to create the main function which will be the basis for any console C / C++ program.
Create a new source file in your environment called main.cpp
We will always use this naming convention for our programs although the file could be called anything. Remember that all code is case-sensitive.

Contents of main.cpp :

Anything following a // is considered a comment and is not compiled into the executable file. This is useful to allow yourself to remember why you did something or to help someone else understand your code. You can also create a comment block by enclosing a section of text within /* and */ symbols.

// This is a comment.
// This tutorial shows you how to create the main method
/* This is a code block spanning over multiple lines :
Line 2
Line 3*/

The main function declaration is shown below. The int keyword shows that the function will return an integer (whole number). This will be explained further in a future tutorial. The name of the method must be main
The brackets that follow allow you to hold parameters that get passed into the function. This will also be explained in a future tutorial but for now we do not want any parameters and therefore a set of empty brackets is shown.

int main()

A function body must be a code block. A code block is enclosed with a { to start the block and a } to end one. This specifies the exact beginning and end of a segment of code.


The return is used to specify the value to return from the function. We spoke about return values earlier on where we said the main function returned an integer. We will return a 0 as this indicates that no error has occurred. A return value of 1 indicates that an error has occurred.
All code statements end with a ; so you must always make sure that your code statements end with one. They are not used at the end of function declarations and at other places which will be shown in later tutorials.

	return 0;

If you now compile and run your program, you will just see a console window flash up on the screen and go away again if you are using windows. The unix / linux executable will appear to do nothing.
This is because we have not programmed anything to happen.

We have progressed from the previous tutorial in that we do not receive any error messages.

The main function will always be the starting point for your code and your first statement in your main function will be the first instruction to be processed in your program.

Please let me know of any comments you may have : Contact Me

Source Files : Visual Studio Dev-C++ Unix / Linux

< Tutorial 02 - Setting Up Your Environment Tutorial 04 - Basic Output >

Back to Top

All Rights Reserved, © Zeus Communication, Multimedia & Development 2004-2005

Read the Disclaimer