Chapter 1. Getting Started
Learning a new programming language requires writing programs.1.1. Writing a Simple C++ Program
1.1.1. Compiling and Executing Our Program
Unless you are already familiar with using your compiler's IDE, it can be easier to start by using the simpler, command-line interface. Using the command-line interface lets you avoid the overhead of learning the IDE before learning the language.Program Source File Naming Convention
Invoking the GNU or Microsoft Compilers
By default the command to invoke the GNU compiler is g++:
$ g++ prog1.cc -o prog1
The Microsoft compilers are invoked using the command cl:
C:/directory> cl -GX prog1.cpp
Running the Compiler from the Command Line
On both UNIX and Windows systems, after executing the program, you must issue an appropriate echo command. On UNIX systems, we obtain the status by writing$ echo $?
To see the status on a Windows system, we write
C:/directory> echo %ERRORLEVEL%
1.2. A First Look at Input/Output
1.2.1. Standard Input and Output Objects
Most operating systems give us a way of redirecting the input or output streams when we run a program. Using redirection we can associate these streams with files of our choosing.1.2.2. A Program that Uses the IO Library
Writing to a StreamUsing Names from the Standard Library
Reading From a Stream
When writing a C++ program, in most places that a space appears we could instead use a newline. One exception to this rule is that spaces inside a string literal cannot be replaced by a newline. Another exception is that spaces are not allowed inside preprocessor directives.
Key Concept: Initialized and Uninitialized Variables
Initialized variables are those that are given a value when they are defined. Uninitialized variables are not given an initial value1.3. A Word About Comments
Comments help the human readers of our programs. They are typically used to summarize an algorithm, identify the purpose of a variable, or clarify an otherwise obscure segment of code.When a comment pair does span multiple lines, it is often a good idea to indicate visually that the inner lines are part of a multi-line comment. Our style is to begin each line in the comment with an asterisk, thus indicating that the entire range is part of a multi-line comment.
It is usually best to place a comment block above the code it explains.
An incorrect comment is worse than no comment at all because it may mislead a subsequent reader.
Comment Pairs Do Not Nest
1.4. Control Structures
1.4.1. The while Statement
Key Concept: Indentation and Formatting of C++ Programs
Our belief is that there is no single correct style but that there is value in consistency.We tend to put the curly braces that delimit functions on their own lines. We tend to indent compound input or output expressions so that the operators line up
When choosing a formatting style, think about how it affects readability and comprehension. Once you've chosen a style, use it consistently.
1.4.2. The for Statement
Compilation Revisited
It is a good practice to correct errors in the sequence they are reported. Often a single error can have a cascading effect and cause a compiler to report more errors than actually are present.
1.4.3. The if Statement
1.4.4. Reading an Unknown Number of Inputs
When we use an istream as a condition, the effect is to test the state of the stream. If the stream is validthat is, if it is still possible to read another input then the test succeeds. An istream becomes invalid when we hit end-of-file or encounter an invalid input, such as reading a value that is not an integer. An istream that is in an invalid state will cause the condition to fail.Entering an End-of-file from the Keyboard
Operating systems use different values for end-of-file. On Windows systems we enter an end-of-file by typing a control-z simultaneously type the "ctrl" key and a "z." On UNIX systems, including Mac OS-X machines, it is usually control-d.1.5. Introducing Classes
1.5.1. The Sales_item Class
Operations on Sales_item Objects
Reading and Writing Sales_items
Headers for the standard library are enclosed in angle brackets ( < >). Nonstandard headers are enclosed in double quotes ( " ").Key Concept: Classes Define Behavior
Adding Sales_items
1.5.2. A First Look at Member Functions
What Is a Member Function?
1.6. The C++ Program
Chapter Summary
Defined Terms
Part I: The Basics
Chapter 2. Variables and Basic Types
2.1. Primitive Built-in Types
The standard guarantees a minimum size for each of the arithmetic types, but it does not prevent compilers from using larger sizes. Indeed, almost all compilers use a larger size for int than is strictly required.Table 2.1. C++: Arithmetic Types
Type | Meaning | Minimum Size |
---|---|---|
bool | boolean | NA |
char | character | 8 bits |
wchar_t | wide character | 16 bits |
short | short integer | 16 bits |
int | integer | 16 bits |
long | long integer | 32 bits |
float | single-precision floating-point | 6 significant digits |
double | double-precision floating-point | 10 significant digits |
long double | extended-precision floating-point | 10 significant digits |
2.1.1. Integral Types
The arithmetic types that represent integers, characters, and boolean values are collectively referred to as the integral types.Typically, shorts are represented in half a machine word, ints in a machine word, and longs in either one or two machine words (on 32-bit machines, ints and longs are usually the same size).
Machine-Level Representation of The Built-in Types
Most computers associate a number called an addresswith each byte in memory.An arithmetic type with value 0 yields a bool that holds false. Any nonzero value is treated as true.
Signed and Unsigned Types
Unlike the other integral types, there are three distinct types for char: plain char, signed char, and unsigned char. Although there are three distinct types, there are only two ways a char can be represented. The char type is respresented using either the signed char or unsigned char version. Which representation is used for char varies by compiler.How Integral Values Are Represented
The C++ standard does not define how signed types are represented at the bit level. Instead, each compiler is free to decide how it will represent signed types. These representations can affect the range of values that a signed type can hold. We are guaranteed that an 8-bit signed type will hold at least the values from -127 through 127; many implementations allow values from -128 through 127.Under the most common strategy for representing signed integral types, we can view one of the bits as a sign bit. Whenever the sign bit is 1, the value is negative; when it is 0, the value is either 0 or a positive number. An 8-bit integral signed type represented using a sign-bit can hold values from -128 through 127.
/ /有符号的整型的具体实现是由编译器来决定的,但无论如何都能保证8位字节的整型的最小取值范围是从-127到127。如果是取其中一位为符号位,以1表示负数,以0表示0或正数。这样的话,它的值就是从-128到127。
Assignment to Integral Types
what happens when one tries to assign a value outside the allowable range to an object of a given type. The answer depends on whether the type is signed or unsigned.
For unsigned types, the compiler must adjust the out-of-range value so that it will fit. The compiler does so by taking the remainder of the value modulo the number of distinct values the unsigned target type can hold.
For the unsigned types, a negative value is always out of range. An object of unsigned type may never hold a negative value. Some languages make it illegal to assign a negative value to an unsigned type, but C++ does not.
In C++ it is perfectly legal to assign a negative number to an object with unsigned type. The result is the negative value modulo the size of the type. So, if we assign -1 to an 8-bit unsigned char, the resulting value will be 255, which is -1 modulo 256.
When assigning an out-of-range value to a signed type, it is up to the compiler to decide what value to assign. In practice, many compilers treat signed types similarly to how they are required to treat unsigned types. That is, they do the assignment as the remainder modulo the size of the type. However, we are not guaranteed that the compiler will do so for the signed types.
2.1.2. Floating-Point Types
The types float, double, and long double represent floating-point single-, double-, and extended-precision values. Typically, floats are represented in one word (32 bits), doubles in two words (64 bits), and long double in either three or four words (96 or 128 bits). The size of the type determines the number of significant digits a floating-point value might contain.
The float type is usually not precise enough for real programs float is guaranteed to offer only 6 significant digits. The double type guarantees at least 10 significant digits, which is sufficient for most calculations.
Advice: Using the Built-in Arithmetic Types
In fact, on some machines, double precision is faster than single. The precision offered by long double usually is unnecessary and often entails considerable extra run-time cost.2.2. Literal Constants
Literals exist only for the built-in types. There are no literals of class types. Hence, there are no literals of any of the library types.Rules for Integer Literals
When specifying a long, use the uppercase L: the lowercase letter l is too easily mistaken for the digit 1.There are no literals of type short.
Rules for Floating-Point Literals
Boolean and Character Literals
We can obtain a wide-character literal of type wchar_t by immediately preceding the character literal with an L, as inL'a'