📄 chapter02.html
字号:
<HTML><HEAD> <TITLE>Chapter 2</TITLE> <LINK REL="STYLESHEET" HREF="downey.css" tppabs="http://rocky.wellesley.edu/downey/ost/thinkCS/c++_html/downey.css"></HEAD><BODY><H2>Chapter 2</H2><H1>Variables and types</H1><BR><BR><H3>2.1 More output</H3><P>As I mentioned in the last chapter, you can put as many statements as you want in <TT>main</TT>. For example, to output more than one line:<PRE>#include <iostream.h>// main: generate some simple outputvoid main (){ cout << "Hello, world." << endl; // output one line cout << "How are you?" << endl; // output another}</PRE><P>As you can see, it is legal to put comments at the end of a line, as well ason a line by themselves.</P> <P>The phrases that appear in quotation marks are called <B>strings</B>, because they are made up of a sequence (string) of letters. Actually, strings can contain any combination of letters, numbers, punctuation marks, and other special characters.</P><P>Often it is useful to display the output from multiple output statements allon one line. You can do this by leaving out the first <TT>endl</TT>:<PRE>void main (){ cout << "Goodbye, "; cout << "cruel world!" << endl;}</PRE><P>In this case the output appears on a single line as <TT>Goodbye, cruel world!</TT>. Notice that there is a space between the word ``Goodbye,'' and the second quotation mark. This space appears in the output, so it affects thebehavior of the program.</P><P>Spaces that appear outside of quotation marks generally do not affect the behavior of the program. For example, I could have written:</P><PRE>void main (){cout<<"Goodbye, ";cout<<"cruel world!"<<endl;}</PRE><P>This program would compile and run just as well as the original. The breaksat the ends of lines (newlines) do not affect the program's behavior either, soI could have written:</P><PRE>void main(){cout<<"Goodbye, ";cout<<"cruel world!"<<endl;}</PRE><P>That would work, too, although you have probably noticed that the program isgetting harder and harder to read. Newlines and spaces are useful for organizing your program visually, making it easier to read the program and locate syntax errors.</P><BR><BR><H3>2.2 Values</H3><P>A value is one of the fundamental things---like a letter or a number---that a program manipulates. The only values we have manipulated so far are the string values we have been outputting, like <TT>"Hello, world."</TT>. You (andthe compiler) can identify string values because they are enclosed in quotationmarks.</P><P>There are other kinds of values, including integers and characters. An integer is a whole number like 1 or 17. You can output integer values the sameway you output strings:</P><PRE> cout << 17 << endl;</PRE><P>A character value is a letter or digit or punctuation mark enclosed in single quotes, like <TT>'a'</TT> or <TT>'5'</TT>. You can output character values the same way:</P><PRE> cout << '}' << endl;</PRE><P>This example outputs a single close squiggly-brace on a line by itself.</P><P>It is easy to confuse different types of values, like <TT>"5"</TT>, <TT>'5'</TT> and <TT>5</TT>, but if you pay attention to the punctuation, it should be clear that the first is a string, the second is a character and the third is an integer. The reason this distinction is important should become clear soon.</P><BR><BR><H3>2.3 Variables</H3><P>One of the most powerful features of a programming language is the ability to manipulate <B>variables</B>. A variable is a named location that stores a value.</P><P>Just as there are different types of values (integer, character, etc.), there are different types of variables. When you create a new variable, you have to declare what type it is. For example, the character type in C++ is called <TT>char</TT>. The following statement creates a new variable named <TT>fred</TT> that has type <TT>char</TT>.<PRE> char fred;</PRE><P>This kind of statement is called a <B>declaration</B>.</P><P>The type of a variable determines what kind of values it can store. A <TT>char</TT> variable can contain characters, and it should come as no surprise that <TT>int</TT> variables can store integers.</P><P>There are several types in C++ that can store string values, but we are going to skip that for now (see Chapter 7).</P><P>To create an integer variable, the syntax is</P><PRE> int bob;</PRE><P>where <TT>bob</TT> is the arbitrary name you made up for the variable. In general, you will want to make up variable names that indicate what you plan todo with the variable. For example, if you saw these variable declarations:</P><PRE> char firstLetter; char lastLetter; int hour, minute;</PRE><P>you could probably make a good guess at what values would be stored in them.This example also demonstrates the syntax for declaring multiple variables withthe same type: <TT>hour</TT> and <TT>second</TT> are both integers (<TT>int</TT> type).</P><BR><BR><H3>2.4 Assignment</H3><P>Now that we have created some variables, we would like to store values in them. We do that with an <B>assignment statement</B>.</P><PRE> firstLetter = 'a'; // give firstLetter the value 'a' hour = 11; // assign the value 11 to hour minute = 59; // set minute to 59</PRE><P>This example shows three assignments, and the comments show threedifferent ways people sometimes talk about assignment statements. Thevocabulary can be confusing here, but the idea is straightforward:</P><OL> <LI>When you declare a variable, you create a named storage location.</LI> <LI>When you make an assignment to a variable, you give it a value.</LI></OL><P>A common way to represent variables on paper is to draw a box with the nameof the variable on the outside and the value of the variable on the inside.This kind of figure is called a <B>state diagram</B> because is shows whatstate each of the variables is in (you can think of it as the variable's ``state of mind''). This diagram shows the effect of the three assignment statements:</P><P CLASS=1><IMG SRC="images/assign.jpg" tppabs="http://rocky.wellesley.edu/downey/ost/thinkCS/c++_html/images/assign.jpg" ALT="Assignment Image"></P><P>I sometimes use different shapes to indicate different variable types.These shapes should help remind you that one of the rules in C++ is that avariable has to have the same type as the value you assign it. For example, you cannot store a string in an <TT>int</TT> variable. The following statementgenerates a compiler error.</P><PRE> int hour; hour = "Hello."; // WRONG !!</PRE><P>This rule is sometimes a source of confusion, because there are many waysthat you can convert values from one type to another, and C++ sometimes converts things automatically. But for now you should remember that as a general rule variables and values have the same type, and we'll talk about special cases later.</P><P>Another source of confusion is that some strings <I>look</I> like integers,but they are not. For example, the string <TT>"123"</TT>, which is made up ofthe characters <TT>1</TT>, <TT>2</TT> and <TT>3</TT>, is not the same thing asthe <I>number</I> <TT>123</TT>. This assignment is illegal:</P><PRE> minute = "59"; // WRONG!</PRE><BR><BR><H3>2.5 Outputting variables</H3><P>You can output the value of a variable using the same commands we used tooutput simple values.</P><PRE> int hour, minute; char colon; hour = 11; minute = 59; colon = ':'; cout << "The current time is "; cout << hour; cout << colon; cout << minute; cout << endl;</PRE><P>This program creates two integer variables named <TT>hour</TT> and <TT>minute</TT>, and a character variable named <TT>colon</TT>. It assignsappropriate values to each of the variables and then uses a series of outputstatements to generate the following:</P><PRE>The current time is 11:59</PRE><P>When we talk about ``outputting a variable,'' we mean outputting the<I>value</I> of the variable. To output the <I>name</I> of a variable,you have to put it in quotes. For example: <TT>cout << "hour";</TT>As we have seen before, you can include more than one value ina single output statement, which can make the previous program moreconcise:<PRE> int hour, minute; char colon; hour = 11; minute = 59; colon = ':'; cout << "The current time is " << hour << colon << minute << endl;</PRE><P>On one line, this program outputs a string, two integers, a character, andthe special value <TT>endl</TT>. Very impressive!<BR><BR><H3>2.6 Keywords</H3><P>A few sections ago, I said that you can make up any name you want for yourvariables, but that's not quite true. There are certain words that are reserved in C++ because they are used by the compiler to parse the structure ofyour program, and if you use them as variable names, it will get confused.These words, called <B>keywords</B>, include <TT>int</TT>, <TT>char</TT>, <TT>void</TT>, <TT>endl</TT> and many more.</P><P>The complete list of keywords is included in the C++ Standard, which is theofficial language definition adopted by the the International Organization forStandardization (ISO) on September 1, 1998. You can download a copy electronically from</P><PRE> <A HREF="javascript:if(confirm('http://www.ansi.org/ \n\nThis file was not retrieved by Teleport Pro, because it is addressed on a domain or path outside the boundaries set for its Starting Address. \n\nDo you want to open it from the server?'))window.location='http://www.ansi.org/'" tppabs="http://www.ansi.org/">http://www.ansi.org</A></PRE>
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -