VC++ Programm Structure

The starting point for C++ programs is the main() function. The previous units showed you some Visual C++ programs. If you look them over, you will see the word main() in every one of them. Looking further still, you will see an opening brace after main() and a closing brace a little later. You never find an opening brace (a left brace) without a closing brace (a right brace). 

Visual C++ programs also share another trait: Almost all of them have one or more lines that begin with the # (pound sign) character, followed by include. Figure 4.1 shows a simple outline of a Visual C++ program. 

Figure 4.1. An Outline of a simple C++ program 



Notice that there is a closing brace for every opening brace? There is also a closing parenthesis for every opening parenthesis and a closing bracket for every opening bracket that appears in a program. The parentheses, braces, and brackets enclose language elements within the Visual C++ program. As with parentheses in written languages, these Visual C++ symbols enclose pieces of a program, and you must indicate with the closing character where the piece ends. Unlike a written document, the meaning of parentheses, braces and brackets are quite distinct in C++ and each must be used in the correct way. 

Before you know it, you will be comfortable with main(), #include, braces, and all the other parts of a Visual C++ program. The next section looks at a longer Visual C++ program and dissects pieces of it to ease you into Visual C++. 



Being able to understand main(), #, and braces is your first step in understanding Visual C++. 



There is no Stop and Type part here due to the textual nature of this section. 


Dissecting a Program




Look at the specific parts of a typical Visual C++ program to acquaint yourself with the code. 

The next few pages provide a closer examination of the program in Listing 4.1. The idea is to give you a look at the big picture before getting into the specific language elements starting in Lesson 3. 

Listing 4.1. A sample Visual C++ program. 

// Filename: DISSECT.CPP  // Simple program for you to analyze  #include   void main()    {      int age, weight;   // These lines define four variables      char initial;      float salary;      age = 13;          // Assigns an integer literal to age      weight = age * 6;  // Assigns a weight based on a formula      initial = 'D';     // All character literals are                         // enclosed in single quotes      salary = 200.50;   // salary requires a floating-point                         // value because it was defined to                         // be a floating-point      salary = salary * 2.5; // Changes what was in salary  // Next line sends the values of the variables to the screen      cout <<>

Keep in mind that this program is simple and does not actually perform a lot of valuable work. Despite its simplicity, you might not fully understand it all even after the explanation that comes next, but it is a good place to begin. 

While looking through the program, see whether you can understand any or all of it. If you are new to programming, you should know that the computer reads each line of the program, starting with the first line and working its way down, until it has completed all the instructions (the statements on each line) in the program. (Of course, you first have to compile and link the program, as described in Lesson 1, before seeing the output from the program on your computer.) 

Here is the output that results when you run this program: 

13, 78, D, 501.25

The Program


After the previous unit, you know all about the first two lines in the program. They contain comments that describe the filename and a little about the program. Comments also are scattered throughout the code to explain what happens along the way. 

The next line is called a preprocessor directive. It is repeated here: 

#include 

This strange-looking statement is not actually a Visual C++ command, but it is a directive to the Visual C++ compiler. The directive directs the compiler (that is easy to remember). #include tells Visual C++ to take the filename located inside the angled brackets and load that file into the Visual C++ program at that point. In principle, the preprocessor first reads all the code looking for any lines beginning with a # symbol and acts upon them before compilation takes place. In the case of an #include, the compiler will view the program as if you had typed the contents of the file directly into the program file. In other words, the program grows to become the size of DISSECT.CPP (the program shown in the preceding section) plus IOSTREAM.H. Most files included with #include end in the .H filename extension because these files are header files. 

The header file named IOSTREAM.H comes with your Visual C++ compiler. Header files are a way of telling your program about pieces of code that it needs that are extra to the C++ language. Recall that cout was not part of the C++ language. The header file contains the information that lets the compiler know that cout is a function and not just a made up word. The include files are located in your Visual C++ directory in a subdirectory called INCLUDE. If you want to include a file you wrote (all #include files must be text, such as those created with the Visual C++ editor), you have to put the included filename in quotation marks, like this: 

#include "d:\myFiles\mine.h"


You might see other header files included, either in addition to IOSTREAM.H or in place of it. Sometimes, Visual C++ programmers use a C program that includes the header file named STDIO.H instead of IOSTREAM.H. Notice in Appendix D, "Visual C++ Command Reference," that #include is not listed with all the other Visual C++ commands. #include is not a Visual C++ command; it is simply a pre-command (hence its name, preprocessor directive) that directs the compiler to do something before it compiles the actual commands. In this case, #include tells Visual C++ to include a file from disk at that point in the program. 


Braces and main()


You see these two lines in all of the Visual C++ programs in this book: 

void main()  {


The void always goes with main(). Treat the following text as saying void main(). We'll worry about what void means much later on. 

main() does not always appear toward the top of the program, as it does here. Sometimes main() appears farther down into the code. Wherever main() is, however, it begins the most critical section of any Visual C++ program. When you run the program, the program always begins executing at main(). No matter where main() is located in the program, it is the starting point for the program's execution. Therefore, it makes sense to put main() toward the top of a program. Sometimes, however, a lot of other stuff has to go before main(). No matter what appears before main(), main() begins the program's execution when you run the program. 



Not all programs written in C++ use main() as the starting point. You will not find a main() in a Windows program. Windows programs use WinMain() because Windows programs work in a way very different from ordinary programs. 

main() is called a function. A function is not a command. It is a named section of a program, and its name always ends with a pair of parentheses. A program can have one function or many functions, but every program contains the main() function because the program has to begin somewhere. You can always tell where a function begins because functions always have names that end with parentheses. The parentheses tell Visual C++ that main() is a function and not a command or something else. 



None of the commands in Appendix D contain parentheses. Parentheses are part of function names, but they are never part of command names. 

Because an opening brace follows main(), you can look for the matching closing brace (they always appear in pairs) and find out where main() ends. Every pair of braces in a Visual C++ program encloses something known as a compound statement. In this case, the compound statement is almost as long as the main() function. The next function—if there were one—could go after main()'s closing brace. You can never define a function inside another one. main() must finish before another function can begin being listed in the program. 



A statement ends in a semicolon. A compound statement is made up of a sequence of statements. A compound statement can be used anywhere that a single statement can be used. A compound statement does not need a semicolon following it. A compound statement is often called a block. 

Before you get too sidetracked, you are going to become extremely comfortable with the fact that main() is a function and that braces enclose blocks in a program. Read on to learn more about the rest of this sample program named DISSECT.CPP. There are more important aspects to the program at this stage in the game than fully understanding main(). 



The void before main() is required in simple Visual C++ programs that do not return values to the operating system. You will learn more about void in Lesson 7, "Break it Up With Functions." 


Data


Here are the three lines that follow main()'s opening brace: 

int age, weight;   // These lines define four variables  char initial;  float salary;

definition

variable is a named value that holds data that can be changed.

These three lines define four variables. A variable definition tells Visual C++ exactly what variables will be used in the lines that follow. This variable definition tells the compiler to make room in memory for four values, label them with names, and get ready to use them. Later in the program, values will be stored in those variables. 

definition

constant is a value that cannot be changed but can be named.

definition

literal is an actual constant value stated in the program.

All Visual C++ programs contain both commands and data. The data is always made up of one or more variables, one or more literals, or a combination of both. A literal is sometimes called a constant, but in Visual C++, the word constant actually has another meaning (in most languages, literal and constant are synonymous). 



As the name implies, a variable is data that can change (become variable) as the program runs. A constant remains the same. In real life, a variable might be your salary. It increases over time (you hope). A constant is something that does not change, such as the number of days in February or the fact that Pi is 3.14159. 

A variable is like a box inside your computer that holds something. That something might be a number or a character, a value of another variable, or the result of a calculation. Every variable within the same block is distinguished from others by its unique name. No two variables within the same block can have the same name. You can have as many variables as needed to hold changing data. After you define a variable and give it a value, the variable keeps its value until you change the value or define the variable with something else by putting some other data value into it. The next lesson more fully explains these concepts. 

The three lines of code that follow the opening brace define four variables. The variable definition informs the rest of the program that two integer variables named age and weight, as well as a character variable named initial and a floating-point variable named salary, appear throughout the program. The terms integercharacter, and floating-point basically refer to different types of data. Integers are whole numbers, and floating-point numbers contain decimal places. 

Just as there are different types of variables, there are different types of constants. The first form of constant you should know is a literal. For now, you simply have to understand that a Visual C++ literal is any number, character, word, or phrase whose value is explicitly written when it is used and does not change as the program runs. The following are all valid Visual C++ literals: 

5.6  -34  'W'  "Mary"  18.293345  0.0

As you can see, some literals are numeric and some are character-based. The single and double quotation marks around two of the literals, however, are not part of the actual literals. A single-character literal requires single quotation marks around it, and a string of characters such as "Mary" requires double quotation marks (often called just quotation marks). 

The body of the DISSECT.CPP program (repeated next) assigns values to the defined variables. 

age = 13;                // Assigns an integer literal to age  weight = age * 6;        // Assigns a weight based on a formula  initial = 'D';           // All character literals are                           // enclosed in single quotes  salary = 200.50;         // salary requires a floating-point                           // value because it was defined to                           // be a floating-point  salary = salary * 2.5;   // Changes what was in salary

The first line puts 13 in the integer variable, age. The second line multiplies 6 by the variable age's value to produce the value 78, which is stored in weight. The multiplication sign (*) in Visual C++ works just as an x does in mathematics. The other primary math operators are shown in Table 4.1. 

Table 4.1. The primary math operators.

OperatorMeaningExample
+Addition4 + 5
-Subtraction7 - 2
*Multiplication12 * 6
/Division48 / 12


Use an asterisk (*) for multiplication and not a lowercase x. The computer would confuse the variable name x with the multiplication symbol x if both were allowed. 

When mathematical operators appear on the right side of an equal sign, the program completes the math before assigning the result to a variable. In the statement 

salary = salary * 2.5;   // Changes what was in salary

the multiplication of salary and 2.5 is performed, and then the result is stored in salary. 



Visual C++ follows math rules by calculating multiplication and division before it calculates any addition and subtraction if a combination appears within the same expression. Therefore, the following produces a result of 8, not 10, because C++ multiplies first, even though addition appears to the left. Lesson 4, "Simple Operators," explains math ordering further. 

result = 2 + 3 * 2;   // Stores an 8 in result


Assigning Values to Variables


Use an equal sign (=), called the assignment operator, to put values into variables. The statement 

age = 13;   // Assigns an integer literal to age

puts the literal 13 into the variable named age. 



Think of an equal sign as working exactly as a left-pointing arrow would. The value on the right of the equal sign moves left into the variable on the left of the equal sign. If there is a formula on the right, Visual C++ computes the answer and moves the answer into the variable on the left side of the equal sign. 

In Listing 4.1, you find the following variables: 

age  weight  initial  salary

Because age is an integer, you should put only integers into it. 



A variable must hold a value that matches the variable's type. 


Output to the Screen


The line that begins with cout (pronounced "see-out") at first looks very confusing: 

cout <<>

When the program reaches this line, it prints the contents of the four variables on-screen. 

The output from the line is 

13, 78, D, 501.25

Because there are no other output statements in the program, this line is the only line that produces something you can see when you run the program. The rest of the program either sets up the code (such as main() and the braces) or performs internal data manipulations (such as assigning values to variables). 

cout is not a Visual C++ command, but it acts a lot like one. You will not see cout in Appendix D. cout has no built-in input or output commands. cout is a C++ class, described in the header file IOSTREAM.H. You will learn about classes much later on, but you'll make use of this class earlier because it is so easy to use. cout sends output to an output device, which is usually the screen. There is a special value you can send to cout called endl, which will send a command to start a new line to the screen. 



You can guess at cout's purpose just by looking at the line with cout. The data values are being sent via the double angled brackets (<<)to the cout device. The values following cout go to the screen in the left-to-right order in which they appear. The opposite of cout is cin. cin gets keystrokes from the keyboard. Can you see that the following statement gets a number from the keyboard and stores it in the location called amount? 

cin >> amount;

You have seen that there are two parts to a program: the commands that the program executes, and the data that a program works on. Commands come in two forms: the C++ keywords that the compiler understands implicitly, and extra commands that the compiler can be made to understand with the use of header files. 

Returning to the Operating System


As soon as your Visual C++ program finishes executing, it should return to the operating system so that another program can be run. The return statement at the end of main() ensures that the program returns to the operating system. return is optional when the function is preceded by void, so you do not have to use it for simple returns from functions such as main(). 

The closing brace after the return does two things in this program. It signals the end of a block (begun earlier with the opening brace), which is the end of the main() function, and it signals the end of the program. 

Figure 4.2 repeats the entire program listing with some callouts that label the various parts of the program. 

Figure 4.2. The structure of the simple C++ program. 

Familiarize yourself with the overall look and feel of this program. It helps to see an overview before diving straight into the specifics of the commands. Now that you have a general understanding of the format of Visual C++ programs, you are ready to tackle the language elements. Good luck with your venture into the world of the Visual C++ language particulars, beginning in the next lesson, "Data Basics." 



Until now, there was no way to present you with an end-of-section Stop and Type analysis because you did not know enough about Visual C++ to see one. From now on, you'll see Stop and Type, Review, Input, Output, and Analysis parts at the end of each section in each unit. You should ignore the line numbers (the numbers followed by colons at the start of the lines). These are not part of the code and are provided simply to allow easy reference to parts of the code. 

Listing 4.2 contains another Visual C++ program that you can study in order to find the common elements mentioned in this unit. 



All C++ programs have similarities. Their structure is the same even though they often do very different work. 

Listing 4.2. A Visual C++ program for review. 

1:  // Filename: VARS.CPP  2:  // All programs share common traits  3:  4:  #include   5:  6:  void main()  7:  {  8:    char c;             // Define all variables before  9:    int i;              // you use them  10:    float f;  11:  12:    // The next few lines store literal values  13:    // in the three variables just defined  14:    c = 'W';  15:    i = 64;  16:    f = 12.57;  17:  18:    // Print the values  19:    cout << "c is " <<>

Output 

c is W, i is 64, f is 12.57

Analysis

Lines 1 and 2 are comments that describe the program's filename and a one-line statement about the program. Line 4 is a preprocessor directive that includes a file needed by the rest of the program. For the time being, include this file in all your Visual C++ programs. Later lessons will explain it in more detail. 

You'll find several blank lines scattered throughout the code, such as lines 3, 5, and 11. Visual C++ ignores the blank lines, but the whitespace helps you read the program. 

All programs have a main() function. You can always tell when a word in a C++ program is a function because of the parentheses that follow the name. All functions open with an opening left brace as shown in line 7. The matching right brace, and therefore the main() function, does not end until line 24. 



Not all programs in this book will begin with void preceding main(). Until Lesson 7 explains how and when to use void, follow this book's lead: Use it when you see it, and don't use it when you write your own programs until you understand what void is all about. 

Lines 8, 9, and 10 define three variables of three data types. The next lesson explains variables and data types in lots of detail. The important thing to note here is that you must define all variables before you use them. When you define the variables as done in lines 8 through 10, you tell C++ that you want those variables created. 

Lines 14 through 16 put values in the three variables defined earlier. Until you put values in variables, you should not use those variables. Unlike some other programming languages, C++ does not place zeros in variables before you use them. Therefore, they will contain garbage or random values. 

Lines 19 and 20 are actually one single C++ statement that takes two lines. The cout produces the output shown after the program listing. 

You will understand all of these program details as you progress in this book. For now, try to get familiar with these concepts and see whether you can learn to spot common elements across C++ programs. 

No comments: