vcl03

Trochę ciekawostek – na weekend (czego to ludzie nie wymyślą ...


What You'll Learn About



Entering a Simple Visual C++ Program



Visual C++ Special Characters



Freeform Style



Uppercase and Lowercase



Longer Programs



The Importance of Comments



The Syntax of Visual C++ Comments



Comments Are For You, Too



C-Style Comments



Homework





General Knowledge



Find the Bug



Write Code That. . .



Extra Credit









- 3 -

Style Issues







comments









freeform









language syntax









reserved words









whitespace













What You'll Learn About





Entering a simple Visual C++ program





Visual C++ special characters





Freeform style





Uppercase and lowercase





Longer programs





The importance of comments





The syntax of Visual C++ comments





Comments are for you, too





C-style comments







This unit shows you a few Visual C++ programs. You will learn to familiarize yourself with the look and feel of simple Visual C++ programs. Do not be too concerned about understanding every line in every program. As a matter of fact, the less you worry
about each program's specifics, the better off you will be for this unit.











Entering a 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 <iostream.h>

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.















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, < and >, 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.













Be extremely careful when typing C++ programs. When one special character such as a left brace is needed, a left parentheses will not do!















Freeform Style













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







definition

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 <iostream.h>

void main(){cout<<"I will be a C++ expert!";}

definition

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.















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.















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 <iostream.h>

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 << i << ", " << j << ", " << c << ", " << x << "\n";

return; // Not required, but helpful

}

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 <iostream.h>

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<<i<<", "<<j<<", "<<c<<", "<<x<<"\n";return;

//Not required, but helpful

}











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















The Importance of Comments













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:





It has a point to it.





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





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.















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 <iostream.h>

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 " << avg; // Prints average

return;

}

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 << ctr << endl; // on-screen

}

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 << ctr << endl;

}

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.















Homework











General Knowledge





What is whitespace?





What is meant by freeform?





What does it mean to maintain programs?





What does C++ prefer most, uppercase or lowercase letters in programs?





What are comments?





Why are comments necessary?





What does the compiler do when it sees a comment?





What do all C++ comments begin with?





What is the difference between a C-style comment and a C++-style comment?





What happens when you nest C-style comments?





True or false: Longer programs are more difficult to understand than shorter ones.





True or false: You can substitute parentheses for braces if you feel that the parentheses are more readable.





True or false: Comments are not Visual C++ commands.





True or false: You can nest one C++ comment inside another.





Match the special character on the left with that special character's description on the right.











Special Character



Description





[



Backslash





<



Left bracket





}



Right-angled bracket





|



Right parenthesis





\



Forward slash (or just slash)





]



Left-angled bracket





{



Left parenthesis





)



Right brace





(



Vertical line





>



Left brace





/



Right bracket









There is no What's the Output? section in this unit.















Find the Bug



Here is a comment and a C++ command (the return statement). Where is the problem?









// Go back to the IDE return;

The following program contains three comment bugs. See whether you can determine what is wrong.







// This program computes taxes

#include <iostream.h>

void main()

{

The next few lines calculate payroll taxes

// Computes the gross pay float gross = 40 * 5.25;

float taxes = gross * .40; / Just computed the taxes

cout "The taxes are " << taxes;

return;

}









Write Code That. . .



Tim Peterson wants to put his name at the top of his program using a comment. Write a comment that contains Tim's name using both the C++-style and the C-style approach.





Here is the same program you saw earlier, with one difference: The programmer forgot to precede the comments with double slashes. After trying to compile the program, the programmer looked at the 20 or so error messages and realized what was left out.
See if you can help the programmer correct the program by inserting the proper commenting symbols everywhere they go.







Filename: 1STLONG.CPP

Longer C++ program that demonstrates comments,

variables, constants, and simple input/output

#include <iostream.h>

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 << i << ", " << j << ", " << c << ", " << x << "\n";

return; Not required, but helpful

}

Hint: Count the number of double slashes you put in this program. If you did not add 18 double slashes (or if you added more than 18), try again.











Extra Credit



Of the following five lines, which contain useful comments and which contain redundant ones?













clog << '\n'; // Sends an end-of-line to the error log

radius3 = radius1 + radius2; // Calculates radius3

// The following code contains a C++ program

// The following code tracks your investments

clog << '\n'; // Sends '\n' to clog
  • zanotowane.pl
  • doc.pisz.pl
  • pdf.pisz.pl
  • strefamiszcza.htw.pl
  • Copyright (c) 2009 Trochę ciekawostek – na weekend (czego to ludzie nie wymyślą ... | Powered by Wordpress. Fresh News Theme by WooThemes - Premium Wordpress Themes.