1.1. Writing a Simple C++ Program

Every C++ program contains one or more functions, one of which must be named main . The operating system runs a C++ program by calling main. Here is a simple version of main that does nothing but return a value to the operating system:

int main()
{
    return 0;
}

A function definition has four elements: a return type, a function name, a (possibly empty) parameter list enclosed in parentheses, and a function body. Although main is special in some ways, we define main the same way we define any other function.

In this example, main has an empty list of parameters (shown by the () with nothing inside). § 6.2.5 (p. 218) will discuss the other parameter types that we can define for main.

The main function is required to have a return type of int, which is a type that represents integers. The int type is a built-in type, which means that it is one of the types the language defines.

The final part of a function definition, the function body, is a block of statements starting with an open curly brace and ending with a close curly:

{
    return 0;
}

The only statement in this block is a return, which is a statement that terminates a function. As is the case here, a return can also send a value back to the function’s caller. When a return statement includes a value, the value returned must have a type that is compatible with the return type of the function. In this case, the return type of main is int and the return value is 0, which is an int.


Image Note

Note the semicolon at the end of the return statement. Semicolons mark the end of most statements in C++. They are easy to overlook but, when forgotten, can lead to mysterious compiler error messages.


On most systems, the value returned from main is a status indicator. A return value of 0 indicates success. A nonzero return has a meaning that is defined by the system. Ordinarily a nonzero return indicates what kind of error occurred.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.224.56.29