Now that you have seen variable declaration, C++ expressions, and the basic math operators, let’s take a quick look at the basic structure of a C++ program. All C++ programs must have a main function. This is where the program begins.A function is one or more statements grouped together in a logical manner to accomplish some goal under a common name. The following is a basic C++ program.
int main()
{
return 0;
}
Now, this program will not do much—in fact, it won’t do anything useful at all. It is, however, a valid C++ program. It has a main function that returns an integer value. The main function is where all C++ programs start. This is the starting point for your entire program. All main functions are required by the ANSI (American National Standards Institute) standards to return an integer. The integer is a 0 if the program executes fine, and a 1 if some problem is encountered. This was originally done because some operating systems require any program to return a value telling the operating system that everything is OK. You will see a lot of Windows programmers use a main function that returns a void like the following.
void main()
This will work in some cases, but it is not technically correct. This book endeavors to conform to the ANSI standards and use
return 0.
The next thing to notice about our sample program is the presence of brackets. These brackets are C++’s way of establishing borders around any block of code. (Incidentally, C, Java, and JavaScript™ do the same thing. Learning it here will help you learn other languages as well.). Every time you see an opening bracket, {there must be a matching} closing bracket. You will see a lot more about this when we discuss loops, decision structures, and functions. For now, suffice it to say that brackets form borders around blocks of code.
With all that said, let’s look at a program that has a few statements.
int main()
{
int j;
j = 5;
j++;
return 0;
}
This simple program creates a variable named j, sets the value of that variable to 5, then increments that value by one. This is still not a particularly exciting piece of code, but it does illustrate the basic structure of a C++ program. Three statements are executed, a 0 is returned to indicate that everything is OK, and there are brackets surrounding the main function. If you carefully examine this code, and follow this template in all your programming, then you will do well!
0 comments:
Post a Comment