There is one essential ingredient of all c++ programs, and this is “main()”.
// the most basic c++ program
int main() // declare the main function returning an integer
{ // start execution of the function
return 0; // return zero (indicating program success)
} // end the “main” block
This code has many comments; there are two types of comment:
-
// This is a single-line comment
-
/* This is a multi-line comment, and
it's end is denoted with a */
main() is a special function, and because it's preceded by “int”, this means that the compiler expects it to return an integer. Originally c used to allow “void main()” which means that the compiler doesn't expect any return value from the function, but this was always considered bad practice (you can't tell if a program completed successfully, or had errors otherwise), and now will generate a compiler error.
You will also notice that there are braces (or curly-brackets, {}) in the code above. They indicate a section of code, and can actually be used on their own to denote a distinct block of code.
int main()
{
{
// this is one section of code
}
{
// this is another section of code
}
return 0;
}
While it is good practice to break up code into smaller chunks, if a section of code gets too complicated (i.e. if it does more than one thing), then it really should be broken up into separate functions. I will discuss about calling functions later on.
Another thing that you might notice about the code is that “return 0” is followed by a semi-colon (;). A semi-colon indicated the end of a line of code. It's one of the most common errors in programs when a semi-colon is missed off from the end of a line, as the compiler thinks that the next line is part of the same command.
As it happens, a function is also a single command, so the following is also legal:
int main() { return 0; );
- Command - an individual instruction to the computer. In the case of a function, or other block, then this can be a series of instructions, that can be called as one.
- Comment - a section of code that isn't interpreted by the compiler. Comments are only used by the author, and anyone who has to make sense of the code.
- Function - a section of code that can be called by name. In other languages there is also what is called a procedure which is the same thing, but doesn't return a value to whatever called it. There is an equivalent in c++ which is to use void as the return type. There will be more about this later in the tutorial.