Longer Programs

Even long C++ programs are fairly easy to follow when you use whitespace and break long programs into a series of smaller functions. 

The sample program shown earlier is extremely simple. Some Visual C++ programs require several hundred thousand lines of code. Budding authors would not tackle a sequel to War and Peace; likewise, brand-new Visual C++ programmers should stay away from huge programming projects. Most of the programs you write for a while will be relatively small, maybe only 10 to 100 lines of code. 

Even a large program usually is not one big program stored in one file on the disk. Programmers often break up large programs into a set of smaller programs. The smaller programs work like building blocks, fitting together as needed to handle some kind of programming application. 

Just to give you another early view of a Visual C++ program, here is a program longer than the one you saw earlier. Don't sweat the specifics yet. Glance over the program and start getting used to the variety of special characters that Visual C++ understands. 

// Filename: 1STLONG.CPP  // Longer C++ program that demonstrates comments,  // variables, constants, and simple input/output  #include   void main()    {      int i, j;    // These three lines declare four variables      char c;      float x;      i = 4;       // i is assigned an integer literal      j = i + 7;   // j is assigned the result of a computation      c = 'A';     // Enclose all character literals                   // in single quotation marks      x = 9.087;   // x is a floating-point value      x = x * 12.3;// Overwrites what was in x                   // with something else      // Sends the values of the four variables to the screen      cout <<>

The next few lessons discuss the commands in this program in depth. Again, just to give you an idea of the importance of readability, here is the same program as seen by the Visual C++ compiler, but a very different program indeed to someone who must maintain it later: 

//Filename: 1STLONG.CPP//Longer C++ program that demonstrates  //comments, variables, constants, and simple input/output  #include   void main(){int i,j;//These three lines declare four variables  char c;float x;i=4;// i is assigned an integer literal  j=i+7;//j is assigned the result of a computation  c='A';//Enclose all character literals//in single quotation marks  x=9.087;//x is a floating-point value  x=x*12.3;//Overwrites what was in x with something else  //Sends the values of the four variables to the screen  cout<

Longer programs don't have to be harder to read than shorter ones. 

Uppercase and Lowercase

C++ is extremely picky about your Caps Lock key. Most of a C++ program appears in lowercase letters. 

Although Visual C++ cares little about whitespace, it does know the difference between uppercase and lowercase letters. Most of the time, Visual C++ prefers lowercase letters. Visual C++'s preference for lowercase letters sets it apart from most other programming languages. To many programming languages, the following statements are identical: 

if (netpay > grosspay)  If (NetPay > GrossPay)  IF (NETPAY > GROSSPAY)

To Visual C++, the three lines are extremely different. As you learn the C++ language, you will see when to use lowercase and when to use uppercase. Again, most of the time, you will program in lowercase letters. 

Visual C++ contains a fixed vocabulary of keyword commands (also referred to as reserved words). Appendix D contains a complete list of Visual C++ commands. A command is part of the limited vocabulary that Visual C++ recognizes. For example, the command that transmits a value from one place in the program to another is return. You must use lowercase letters for return, as well as for all the other commands in Visual C++. 

Refer to Appendix D, "Visual C++ Command Reference," often as you learn the commands of Visual C++, especially the specific commands beginning in Lesson 3, "Data Basics." 

If you want to print messages to the screen or to your printer, you can use uppercase, lowercase, or a mixture of both for the message itself. For example, recall that the program shown earlier printed this message to the screen: 

I will be a C++ expert!

Because this is a message for the user of the program to read, you would want Visual C++ to print it using regular uppercase and lowercase characters. Because the message is not a keyword, it does not have to be all lowercase. 

Before you go any further, a short review of the previous sections is warranted. Visual C++ is picky about lowercase commands and about making sure that you type special characters exactly right. Whitespace, however, is another thing entirely. Visual C++ does not care how much whitespace you add to a program for readability. 

For and for are two different words to C++. Be sure to maintain consistency with uppercase and lowercase letters. C++'s preference is usually lowercase letters. 

VC++ Programm Analysis

In this lesson, you learned about the fundamental format of all C++ programs. You saw the following: 

  • Visual C++ programs contain a main() function. 

  • Braces determine where the main() function begins and ends. 

  • Preprocessor directives direct the way Visual C++ compiles your program. Preprocessor directives always begin with a pound sign, #. The #include directive includes files needed by library functions. 

  • Visual C++ comments begin with // and end at the end of the line. Comments are for people, not for Visual C++. 

  • The cout command outputs data to your screen. 

  • All characters are important in Visual C++ programs. 

Project 2 Listing. Introduction to Visual C++ programs. 

1:  // Filename: PROJECT2.CPP  2:  // Introduces the format of Visual C++ programs and demonstrates  3:  // how to write Visual C++ comments, the #include preprocessor  4:  // directive, and the cout command that outputs data to the  5:  // screen.  6:  7:  #include   8:  9:  void main()  10:  {  11:    cout << "I have a ";  12:    cout << "Sleekster";       // Continues the output line  13:    cout << " automobile.";      14:    cout <<>


1: A Visual C++ comment that includes the program's filename.

2: A comment that begins the introduction of the program's description.

3: The program's description continues.

4: The program's description continues.

5: The program's description continues.

6: Extra blanks make your program more readable.

7: The cout command needs information in the IOSTREAM.H header file.

8: Extra blanks make your program more readable.

9: All functions have names and the first function in all Visual C++ programs is main().

10: All functions begin with a left brace.

11: The screen output begins.

12: The car's model name prints. No new line occurs.

13: Finish the output.

14: Move the cursor down two lines.

15: Extra blanks make your program more readable.

16: Another message prints.

17: cout prints all kinds of data. Strings and an integer output here.

18: This cout outputs strings and a character literal.

19: Statements can be more than one line.

20: Extra blanks make your program more readable.

21: The final return; in main() always returns control back to Visual C++'s QuickWin window

22: A closing brace always terminates the main() function.

7: The compiler inserts a helpful file here. 

10: void means that main() does not return a value to the operating system. 

14: endl sends a new line command to the screen.


      I have a Sleekster automobile.  I want to sell my car for $4800 (cheap!).  I have had the car for 5 years.  It's really a grade-A deal!

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: 


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." 


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

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


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. 


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


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.

+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 " <<>


c is W, i is 64, f is 12.57


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. 

The Syntax of Visual C++ Comments

Begin all comments with two slashes, //. 

In computer lingo, language syntax refers to the spelling of commands, the ordering of special characters, and the placing of the language elements. When you learn the syntax for a Visual C++ command or operation, you learn the exact format required so that Visual C++ knows what you want it to do. 

Comments are so important that you are now going to learn the syntax of comments (how to write comments so that Visual C++ knows that they are comments) before you learn any Visual C++ commands. Use comments abundantly so that someone reading your program later has a clear guide to the program's contents. A Visual C++ programmer might be able to trace through your Visual C++ code and figure out what the program does, but comments speed the process. The faster someone understands your code, the faster he or she can make any needed changes and move on to other projects. 

A comment begins with two forward slashes, sometimes called a double slash. Comments extend to the end of the line. In other words, you cannot have a command, a comment, and then another command all on the same line. Here is an example of a Visual C++ line with a comment: 

return ((a > b)?a:b);  // Grabs the larger of two values

Here is the same line without the comment: 

return ((a > b)?a:b);

With a comment, you don't even have to know Visual C++ in order to know what the statement is doing. Without a comment, as you can see, the statement looks like garbage characters that make no sense. 

The double slash is vital: without it, Visual C++ would refuse to accept the line. Even though return ((a > b)?a:b); is a valid Visual C++ command, if you left out the double slash comment signal, Visual C++ would see the words Grabs the larger of two values and not know what to do with them. After all, Visual C++ does not know English; it knows only C++. The comment is there not for Visual C++ but for a person looking through your program. 

Comments can reside on lines all by themselves. Sometimes you use comments for more than one program statement. Comments are useful for describing a section of several lines in a program and for putting in program notes about the programmer and the program. For example, the following small Visual C++ program contains two lines of comments that extend the entire line length, as well as three additional comments to the right of Visual C++ code. 

// Filename: COMAVGE.CPP  // Program to compute the average of three values  #include   void main()    {      float g1, g2, g3;   // Variables to hold student grades      cout << "What grade did the first student get? ";      cin >> g1;      cout << "What grade did the second student get? ";      cin >> g2;      cout << "What grade did the third student get? ";      cin >> g3;      float avg = (g1 + g2 + g3) / 3.0;   // Computes average      cout << "The student average is " <<>

All of the programs on this book's program disk are stored under a separate filename. You must tell your Visual C++ compiler the program's filename before it can load the program into memory and run it. To help you quickly try the examples throughout this book, a comment on the first line of every program contains the name of the program as it is stored on the disk. For instance, you can load the preceding program from the book's program disk by retrieving the file named COMAVGE.CPP. 

Many companies require their programmers to put their names in comments at the top of programs they write. If someone later has a question about the program, the original programmer can be traced. If several people make changes to a program, they often put their names too, with a brief comment about the changes they made. Because all these types of lines are commented, Visual C++ skips over them, as it should. Often, they also put a brief description of what the program is supposed to do at the beginning. 

Scatter comments throughout a program as well. If you write some tricky code that needs explanation, spend a few lines of comments, if needed, explaining what the next few lines of code do. 

Be proud of yourself! You do not yet know one bit of Visual C++ code, yet you understand exactly what the preceding program does. That's the purpose of comments! They document a program so that you don't have to go through tedious code to learn what parts of the program are doing. 

A Visual C++ programmer usually can understand what a simple Visual C++ program is supposed to do, even if the program has no comments at all. As soon as you learn the Visual C++ language, you will be able to look through straight Visual C++ code, with no comments, and make changes that need to be made. The comments simply help describe what the program is doing. 

Comments begin with // and extend to the end of the line. You can put comments on lines by themselves or at the end of other C++ code. 

Comments Are For You, Too

Even if you write programs that you will maintain yourself, you'll need comments. 

Suppose that you write programs for your own use and amusement. Nobody but you will ever see the Visual C++ code you write. Can you think of why you should take the time to add comments to your own programs? There are plenty of reasons. 

Suppose that you write a Visual C++ program to track your bank records. A year later, your bank allows for automatic transfers of utility bill payments straight from your savings account. Your old program no longer suffices for the new banking system, so you get the Visual C++ code out and begin making changes. However, you can't remember what you did before, and the code is so succinct that it is difficult to follow. Luckily, you put comments in the code, so you read through the program until you get to the place you need to change. As soon as you are there, you know what is going on in the code, and you quickly make the changes. 

Get into the habit of commenting as you write programs. Many people write programs without commenting as they go, thinking that they will add comments later. More often than not, the comments never get added. When program maintenance is required, it takes twice as long to change the code as it would if the programmer had added comments during the original programming phase. 

As important as comments are, you can over-comment a program. Add comments to lines only when the program's code warrants it. You see many more comments in the first few programs in this book than you see later. As you learn the simple commands, this book attempts to clarify them through extra comments in the program listings. 

Nevertheless, redundant comments are as bad as no comments at all. For example, even though you know nothing about Visual C++ commands, you might agree that the following code contains worthless comments: 

totalsales = oldsales + newsales;   // Adds the old sales and                                      // the new sales to get                                      // total sales  cout << "Happy Birthday";   // Sends the Happy Birthday                              // message to the cout  return;   // Return

Each of these comments is redundant, and they really do not explain what is going on any more than the Visual C++ code itself. However, consider this statement: 

for (int ctr = 10; ctr > 0; ctr) // Prints the numbers    {                              // from 10 to 1      cout <<>

Although you don't know Visual C++ (and even if you did), you can see that the purpose of these two lines of code is hidden in the cryptic Visual C++ language. A Visual C++ programmer could figure out this code, but the comment makes it effortless. As you saw in the previous three code fragments, comments often span more than one line. Continue a comment on the next line (remembering to use a double slash) if it is too long to place on a single line. 

It is also useful to describe in your comments why your program is doing something. In the previous snippet, it would be obvious to a C++ programmer that the program was putting the numbers on the screen. If this was part of a graph drawing program, it might be more helpful to comment it like this: 

//  //  Display the range of the graph on the screen  //  for (int ctr = 10; ctr > 0; ctr)     {      cout <<>

Now you understand why the program has a piece of code in it. 

After writing a program, you'll need comments even if you maintain the program yourself. Use comments only when they help explain what is going on in the code. 

C-Style Comments

Visual C++ supports your use of the old C-style comments that begin with /* and end with */. 

Visual C++ supports another kind of comment that you might see occasionally. Visual C++ is based on the C language, but Visual C++'s comment syntax differs from C's. The designers of Visual C++ decided to keep the old C-style comment syntax so that C programs would work, with little or no change, with Visual C++ compilers. Nevertheless, the double slash comments are considered superior. You should learn C comments just in case you see them. 

A comment in C begins with the characters /* and ends with the characters */. Unlike with Visual C++ comments, you must end a C comment. If you do not put the ending */, C assumes that the next line (or the next hundred lines) is still a comment until it finally finds another */. The following line contains a C-style comment: 

char name[25];   /* Reserves space for a 25-character name */

Because a C comment ends only when the */ is reached, the following three lines make up a single comment: 

/* The following program calculates stock statistics  using the most modern technical analysis techniques  available. */

Of course, the three lines could also be commented like this: 

/* The following program calculates stock statistics */  /* using the most modern technical analysis techniques */  /* available. */

Although you should become familiar with C comments, true Visual C++ programmers tend to avoid using them. The double slash is easier because you don't have to remember to end the comment. The C-style comments can be error-prone as well. If you embed one C-style comment within another, Visual C++ gets confused. Stay with Visual C++ comments as much as possible, and both you and your Visual C++ compiler will lead healthier and more productive lives. 

C comments can be dangerous if you accidentally embed one within another. Stick to C++'s // comment style. There might be times, however, when you run across C comments in a C++ program and you should understand their format. 


Provide readable comments that explain in plain language (non-C++) what's going on. 

Suppose that your car breaks down in the middle of nowhere with no other cars in sight. The problem is not tools or parts; they are in the trunk. The problem is that you know absolutely nothing about the car, and when you open the trunk, you have no clue as to where the parts go or how to fix the problem. 

Just about to despair, you glance down and see two car repair books in the trunk. You pick up the first one and realize that it is a book written by advanced, expert mechanics for advanced, expert mechanics. The book uses technical jargon you've never heard. You toss the worthless repair book over your shoulder and pick up the next book. The title is Car Repair for the Un-Mechanic. Glancing through the opening pages, you begin to smile. The second book assumes that you don't know a rotor widget #4 from a tactile stem #3B-7. The second book explains, in uncluttered and nonmechanical language and with a friendly style, exactly how to fix your problem. 

You find that the second book contains the very same facts that the first one does. Of course, the first book does not help your plight one bit. It teaches you nothing and explains nothing. It assumes that you know enough to write the book yourself. The second book explains every concept in easy-to-understand language, and in 10 minutes, you fix the car just in time to drive to the cafe across the street for dinner. (You thought you were in the middle of a desert or something?) 

Which of the following is true of this car story: 

  1. It has a point to it. 

  2. It mistakenly got mixed in with this book at the printer. 

  3. It proves that this book's author cannot focus on one subject for very long. 

Obviously, the story has a point (and also hints at number 3). The point is that people react much better to material that is not technically above their heads. Of course, any subject is easy if it is explained well enough. If thermonuclear space transportation were explained in a simple manner, you could understand it. 

By their very nature, Visual C++ programs are cryptic, even to established C++ programmers. As the previous lesson explained, programs rarely remain in one form. The life of a programmer includes not only writing new programs, but updating programs written earlier. As you write a Visual C++ program, add whitespace so that the program is easier to read. Even more important, add comments as well. 

Comments are not Visual C++ commands. As a matter of fact, Visual C++ ignores any and all comments in your programs. Comments are nothing more than messages that explain what the program does. Comments are for people, not for the computer. 

If your Visual C++ programs contain only Visual C++ code and no comments, they will be virtually impossible to figure out later. Remember that Visual C++ is cryptic and extremely difficult to read. Many companies that employ programmers require that their programmers put comments throughout every program they write. Why do you think these companies require comments? It is because people change, jobs change, and companies must ensure that a program written by one person can be understood by the next person. 

Freeform Style

C++'s freeform style lets you insert spacing and blank lines throughout your code to help make the program more readable. 


Whitespace consists of the blank lines and indentations you add to code.

Most of the time, you can put lots of spacing in a Visual C++ program and C++ will not complain. You can put whitespace between symbols and the words that make up the C++ language (but you can't split up words with spaces). C++ programmers often put extra spaces and blank lines in programs to make the programs more readable. With whitespace, C++ programmers make C++ programs more readable to people, not to the Visual C++ compiler. 

To your Visual C++ compiler, the following program is exactly the same program as the previous one you saw: 

//Filename:CFIRST.CPP//Program displays a message on-screen  #include   void main(){cout<<"I will be a C++ expert!";}


Freeform means that C++ lets you insert as many spaces and lines as you want.

Which is easier for you to read, the first or the second version of the program? Obviously, the first version is. Visual C++ is called a freeform compiler. You can indent lines of the program, or leave all the lines flush left. 

Because your computer is a machine, it does not require extra whitespace to understand a program. As long as you follow all the coding rules of Visual C++, the compiler will be happy with the code you supply. In spite of the Visual C++ compiler's lack of concern for how nice a program looks, you should be concerned about the program's look. Add extra whitespace to group similar lines of code together and make the program easier to understand for people who read the program. 

As you see other programs throughout this book, you will begin to pick up some C++ whitespace conventions and develop some of your own. 

Programs Always Change 

While you write Visual C++ programs, consider that someday you might have to change those programs or somebody you work with will have to. You could squeeze as much space out of a program as possible, but you will gain nothing from doing so. (You might save a few characters of computer memory, but not enough to make up for a messy program.) 

If you add extra whitespace to make the program more readable to people, the program will be easy to modify in the future. In this ever-changing world, programs have to be modified to reflect those changes, and the person who writes more readable code gets hired for programming jobs faster than one who does not care about program readability. Updating and changing programs is called maintaining programs. A maintainable program is a readable program.

If you are confused now, you are right on track! You still do not have to understand any specifics about the two program listings seen so far. This unit is getting you used to the look and feel of Visual C++ programs, not their particulars. If you understand that Visual C++ is picky about the characters you type, and if you realize that a program should be readable to people, you deserve an A+ for the unit so far. 

The C++ freeform language allows for as much whitespace as you want to add. 

Visual C++ Special Characters

C++ is a language rich in special characters. 

Visual C++ is one of the few programming languages that uses almost every key on your keyboard. Visual C++ is picky about the keys you press. Notice that the program in the preceding section contains a left and a right brace, { and }. If you were to use parentheses, ( and ), or square brackets, [ and ], in place of the braces, Visual C++ would complain. Make sure that you also distinguish between left and right angled brackets, <>, as well as the forward slash, /, and the backslash, \. 

Be extremely careful to use the characters you are supposed to use. Computers are precise machines without as much tolerance for typing ambiguities as people have. Throughout Visual C++ Programming in 12 Easy Lessons, you will learn when to use each of the characters and what they mean. Until then, be very careful to type the correct characters. 

Visual C++ distinguishes between a capital letter O and a number 0 (zero). Also, a lowercase letter l will not substitute for a number 1. Because you're dealing with a machine, you should type numbers when C++ wants numbers, letters when C++ wants letters, and exact special characters (characters that are neither letters nor numbers, such as brackets and the plus sign) when C++ wants them. 

Simple Visual C++ Program

Enter and run a simple Visual C++ program and discuss the code and results. 

Here is a Visual C++ program. Although it is extremely simple, it contains all the elements necessary to be a valid Visual C++ program. 

// Filename: CFIRST.CPP  // Program displays a message on-screen  #include   void main()    {      cout << "I will be a C++ expert!";    }

Even a simple Visual C++ program might intimidate a beginning programmer. Do not let it intimidate you! C++ has a bark that is often worse than its bite. If you were to type this program into your Visual C++ compiler's editor, compile it, and run it, you would see the following output on your screen: 

I will be a C++ expert!

At this point, do not concern yourself with the specifics of the code in this program. The rest of this book explains things like that. Only one line in the entire seven-line program does anything noticeable (the one that begins with cout), and the rest of the program is simply there because C++ needs it to be there. You will find out why as you work through the unit. 

The preceding program contains a total of seven lines, and only one really produces something you can see. More advanced Visual C++ programs might consist of 500 lines or more. That 7-to-1 setup-to-work ratio does not exist for every Visual C++ program. That would cause too much work on your part! The amount of code that sets up the program diminishes as a program grows. 

C++ programs sometimes look cryptic, but when you learn the fundamentals of the language, you'll see that program formats are often similar. A simple program might contain several lines of code. 

There are no Stop and Type parts in this unit due to the textual nature of the material. 

Programming with Visual C++

the fundamentals of the Visual C++ compiler and how to enter and edit programs using Visual C++'s workbench. You saw the following: 

  • Introduction to programming concepts 

  • How C++ compares to other languages 

  • Starting Visual C++ 

  • Using Visual C++'s menus 

  • How to enter and edit Visual C++ programs 

  • How to compile Visual C++ programs 

  • Stopping Visual C++ 

This project reviews entering and editing a Visual C++ program using the workbench. You are not expected to understand how the program works. The format of future projects will concentrate much more on Visual C++'s language specifics using a different project format. 

Step 1: Start Visual C++. 

Before using Visual C++, you must start the workbench. Follow these steps: 

  1. Turn on your computer. 

  2. Start Windows by typing WIN (if it does not automatically start Windows). 

  3. For Windows 3.1, choose the program group Microsoft Visual C++. Double-click on the icon titled Visual C++. 

    For Windows 95, click on the Open button, choose Programs from the popup menu, and select Microsoft Visual C++. Click on Visual C++. 

Step 2: Open a program window. 

  1. The Visual C++ workbench is known as an MDI application. You enter and edit programs in one or more windows that appear in the workbench. Before typing a new program, you must open a new file in a new window. Type Alt+F,N (File New) to open a new file in an editing window. 

    Although I describe keystrokes to issue the commands, feel free to use the mouse to select menu options. Neither is a better way to use Windows; just use the way that is easiest for you. 

  2. Type the following program. When typing the program, be sure to press Enter at the end of each line (including the very last line). Type as accurately as possible so that no mistakes appear later. The program takes more lines than will fit in the workbench editing window, so you'll see the workbench scroll downward when you fill the open window. 

    Project 1 Listing. The Visual C++ project program. 

    // Filename: PROJECT1.CPP  // Prints the first 20 odd, then even, numbers.  // Once done, it prints them in reverse order.  #include   void main()    {      int num;   // The for loop control variable      cout << "The first 20 odd numbers:\n";      for (num = 1; num < num =" 2;" num =" 39;">= 1; num -= 2)        { cout << num =" 40;">= 2; num -= 2)        { cout <<>

  3. When you finish typing the complete program, you can use PageUp, PageDown, and the arrow keys to scroll the top of the program back into view. 

Step 3: Compile and run the program. 

  1. Before running the program, you must compile it. Choose Project | Build, (Shift+F8) which is an alternative to Project | Execute when you know the program needs to be made. 

  2. If errors appear, the status bar will display an error count. Pressing F4 guides you through the code and leaves you near where the errors are. You can fix any errors that might appear. Recompile the program when you type it exactly as the listing shows. 

  3. If no errors appear, the error count will be zero and you can then press Ctrl+F5 to execute the program. Here is what you'll see in the QuickWin window: 

    The first 20 odd numbers:  1 3 5 7 9 11 13 15 17 19 21 23 25 27 29 31 33 35 37 39  The first 20 even numbers:  2 4 6 8 10 12 14 16 18 20 22 24 26 28 30 32 34 36 38 40  The first 20 odd numbers in reverse:  39 37 35 33 31 29 27 25 23 21 19 17 15 13 11 9 7 5 3 1  The first 20 even numbers in reverse:  40 38 36 34 32 30 28 26 24 22 20 18 16 14 12 10 8 6 4 2

  4. Close the output window and return to the workbench's editing window (use Alt+Tab or click on the workbench window if you do not directly return to the workbench). 

Step 4: Save your work. 

If you exit Visual C++ without saving your program, you'll lose the program and have to reenter it in order to see the results again. Therefore, you'll want to save your programs to a disk file. 

All of the programs in this book, including the one shown in Listing 1, are stored on the enclosed program disk. You don't have to save this listing unless you want the practice, because it is already on the disk. 

  1. To save a program, select Alt+F,S (for File Save). You'll see the File Save dialog box appear on the screen. 

  2. Type a program name along with a path name if you want to store the program in a subdirectory. All Visual C++ programs should end with the .CPP filename extension. 

Step 5: Exit Visual C++. 

  1. Select Alt+F4 (for File Exit) to close Visual C++. If you did not save your program, Visual C++ tells you with a final dialog box that gives you one last chance to save the program. 

  2. After saving the program, you can exit Visual C++ and switch off your PC. You should always return to DOS with Windows 3.1 or shut down your PC under Windows 95 before powering off your computer. 

ATL Server Project

This project shows how to access a database from web, A online store is used as an example. On executing the application, a Web page comes up and asks you for a username and password. You can create a new account or enter a username and password for an existing customer in the database, in first case the application will write the new username and password to the database.

Building and Running the Sample
To build and run this sample
Open the solution file, Tutorial.sln, in the Visual Studio development environment.

Build the solution. This will also deploy the solution to the local Web server.

Configure the data link to connect to the Tutorial.mdb database. In the sample's Tutorial\Tutorial\bin directory, double-click Tutorial.udl.

The Data Link Properties dialog box appears.

On the Provider tab, select Microsoft Jet 4.0 OLE DB Provider.

On the Connection tab, click the Ellipsis (...) button to specify the Tutorial.mdb file in the Tutorial\Tutorial\bin directory. Leave the username and password blank.

Ensure that Tutorial.mdb is not read-only. Right-click the file and select Properties. On the General tab, ensure that the Read-only check box is cleared.

Change the NTFS security settings on the Tutorial.mdb file to allow read-write access by the Internet Guest Account, IUSR_Machine. To do this:

Right-click the Tutorial.mdb file and select Properties on the shortcut menu.

In the Properties dialog box, select the Security tab and click Add.

The Select Users or Groups dialog box appears; in that dialog box, set the following:

Object Types to Users.

Locations to the local machine.

Check Names to IUSR_Machine.

Select the Internet Guest Account that you just created. In the Permissions box, select the Read and Write boxes if they are not already selected.

See ATL Server Security for information about the accounts used by a typical ATL Server application running in IIS.

Change the NTFS security settings on the folder containing Tutorial.mdb to allow only write access by IUSR_Machine, using the procedure described in Step 7.

Change the NTFS security settings on the Tutorial.udl file to allow read access by the IUSR_Machine account, using the procedure described in Step 7.

Use a Web browser to view http://localhost/tutorial/login.srf.

for source file - > http://www.technicalcontents.com/visualc