Fundamentals of
Programming
C
++
DRAF
T
Richard L. Halterman
School of Computing
Southern.Adventist University
January 27, 2013
i
Contents
1 The Context of Software Development 1
1.1 Software . . . 2
1.2 Development Tools . . . 2
1.3 Learning Programming with C++ . . . 5
1.4 Summary . . . 6
1.5 Exercises . . . 6
2 Writing a C++ Program 7 2.1 General Structure of a Simple C++ Program . . . 7
2.2 Compiling the source code . . . 9
2.3 Variations of our simple program . . . 14
2.4 Template for simple C++ programs . . . 17
2.5 Summary . . . 18
2.6 Exercises . . . 19
3 Values and Variables 21 3.1 Integer Values . . . 21
3.2 Variables and Assignment . . . 23
3.3 Identifiers . . . 26
3.4 Floating-point Types . . . 29
3.5 Constants . . . 31
3.6 Other Numeric Types . . . 31
3.7 Characters . . . 32
3.8 Enumerated Types . . . 34
3.9 Type Inference with auto . . . 35
CONTENTS ii
3.11 Exercises . . . 38
4 Expressions and Arithmetic 41 4.1 Expressions . . . 41
4.2 Mixed Type Expressions . . . 46
4.3 Operator Precedence and Associativity . . . 50
4.4 Comments . . . 52
4.5 Formatting . . . 53
4.6 Errors and Warnings . . . 55
4.6.1 Compile-time Errors . . . 55
4.6.2 Run-time Errors . . . 56
4.6.3 Logic Errors . . . 58
4.6.4 Compiler Warnings . . . 58
4.7 Arithmetic Examples . . . 60
4.8 More Arithmetic Operators . . . 63
4.9 Algorithms . . . 66 4.10 Summary . . . 68 4.11 Exercises . . . 70 5 Conditional Execution 75 5.1 Type bool . . . 75 5.2 Boolean Expressions . . . 76
5.3 The Simple if Statement . . . 78
5.4 Compound Statements . . . 81
5.5 The if/else Statement . . . 82
5.6 Compound Boolean Expressions . . . 86
5.7 Nested Conditionals . . . 89
5.8 Multi-way if/else Statements . . . 97
5.9 Errors in Conditional Statements . . . 101
5.10 Summary . . . 102
5.11 Exercises . . . 103
6 Iteration 107 6.1 The while Statement . . . 107
CONTENTS iii
6.3 Abnormal Loop Termination . . . 126
6.3.1 The break statement . . . 126
6.3.2 The goto Statement . . . 127
6.3.3 The continue Statement . . . 129
6.4 Infinite Loops . . . 130
6.5 Iteration Examples . . . 134
6.5.1 Drawing a Tree . . . 134
6.5.2 Printing Prime Numbers . . . 137
6.6 Summary . . . 140
6.7 Exercises . . . 141
7 Other Conditional and Iterative Statements 147 7.1 The switch Statement . . . 147
7.2 The Conditional Operator . . . 151
7.3 The do/while Statement . . . 152
7.4 The for Statement . . . 155
7.5 Summary . . . 161
7.6 Exercises . . . 162
8 Using Functions 167 8.1 Introduction to Using Functions . . . 168
8.2 Standard Math Functions . . . 173
8.3 Maximum and Minimum . . . 176
8.4 clock Function . . . 177 8.5 Character Functions . . . 179 8.6 Random Numbers . . . 180 8.7 Summary . . . 184 8.8 Exercises . . . 185 9 Writing Functions 187 9.1 Function Basics . . . 188 9.2 Using Functions . . . 196 9.3 Call by Value . . . 201 9.4 Function Examples . . . 202
CONTENTS iv
9.4.2 Command Interpreter . . . 204
9.4.3 Restricted Input . . . 206
9.4.4 Better Die Rolling Simulator . . . 207
9.4.5 Tree Drawing Function . . . 209
9.4.6 Floating-point Equality . . . 210
9.4.7 Multiplication Table with Functions . . . 213
9.5 Commenting Functions . . . 216
9.6 Custom Functions vs. Standard Functions . . . 218
9.7 Summary . . . 220 9.8 Exercises . . . 221 10 More on Functions 227 10.1 Global Variables . . . 227 10.2 Static Variables . . . 235 10.3 Overloaded Functions . . . 238 10.4 Recursion . . . 239
10.5 Making Functions Reusable . . . 244
10.6 Pointers . . . 249
10.7 Call by Reference . . . 254
10.7.1 Call by Reference via Pointers . . . 255
10.7.2 Call by Reference via References . . . 257
10.8 Function Pointers . . . 258
10.9 Summary . . . 260
10.10Exercises . . . 261
11 Arrays 269 11.1 Declaring and Using Arrays . . . 271
11.2 Arrays and Functions . . . 279
11.3 Prime Generation with an Array . . . 282
11.4 Multidimensional Arrays . . . 284
11.5 Pointers and Arrays . . . 287
11.6 Array Ranges . . . 291
11.7 C Strings . . . 292
11.8 Dynamic Arrays . . . 295
CONTENTS v 11.10Copying an Array . . . 302 11.11Memory Management . . . 303 11.12Summary . . . 307 11.13Exercises . . . 308 12 Array Algorithms 313 12.1 Sorting . . . 313 12.2 Flexible Sorting . . . 316 12.3 Search . . . 319 12.3.1 Linear Search . . . 319 12.3.2 Binary Search . . . 322 12.4 Array Permutations . . . 330
12.5 Randomly Permuting an Array . . . 337
12.6 Summary . . . 344
12.7 Exercises . . . 344
13 Standard C++ Classes 347 13.1 String Objects . . . 348
13.2 Vectors . . . 351
13.2.1 Declaring and Using Vectors . . . 352
13.2.2 Copying Vectors . . . 354
13.2.3 Vectors and Arrays . . . 360
13.3 Input/Output Streams . . . 362 13.4 File Streams . . . 366 13.5 Complex Numbers . . . 370 13.6 Summary . . . 371 13.7 Exercises . . . 373 14 Custom Objects 375 14.1 Object Basics . . . 375 14.2 Fields . . . 377 14.3 Methods . . . 383 14.4 Constructors . . . 390 14.5 Destructors . . . 392
CONTENTS vi
14.7 Encapsulation . . . 396
14.8 Summary . . . 399
14.9 Exercises . . . 400
15 More on Objects 407 15.1 Pointers to Objects and Object Arrays . . . 407
15.2 The this Pointer . . . 410
15.3 const Methods . . . 412
15.4 Separating Method Declarations and Definitions . . . 414
15.5 Preventing Multiple Inclusion . . . 421
15.6 Overloaded Operators . . . 424 15.6.1 Operator Functions . . . 424 15.6.2 Operator Methods . . . 428 15.7 static Members . . . 429 15.8 Classes vs. structs . . . 433 15.9 Summary . . . 434 15.10Exercises . . . 435
16 Building some Useful Classes 437 16.1 A Better Rational Number Class . . . 437
16.2 Stopwatch . . . 440
16.3 Sorting with Logging . . . 446
16.4 Linked Lists . . . 450
16.5 Automating Testing . . . 461
16.6 Summary . . . 465
16.7 Exercises . . . 465
17 Inheritance and Polymorphism 467 17.1 I/O Stream Inheritance . . . 467
17.2 Inheritance Mechanics . . . 469
17.3 Uses of Inheritance . . . 472
17.4 Polymorphism . . . 479
17.5 Protected Members . . . 485
17.6 Fine Tuning Inheritance . . . 494
CONTENTS vii
17.8 Exercises . . . 506
18 Generic Programming 509 18.1 Function Templates . . . 509
18.2 Class Templates . . . 516
18.3 The Standard Template Library . . . 526
18.4 Iterators . . . 526 18.5 Summary . . . 528 18.6 Exercises . . . 528 19 Exception Handling 529 19.1 Summary . . . 529 19.2 Exercises . . . 529 Appendices 533 A Visual C++ Command Line Development 533 B Developing C++ Programs under Unix/Linux with the GNU Tools 537 C Introduction to Binary Numbers and Computer Arithmetic 539 C.1 The Integer Types . . . 539
C.2 The Floating-Point Types . . . 544
D Bitwise Operators 549
Bibliography 553
ix
Preface
Legal Notices and Information
Permission is hereby granted to make hardcopies and freely distribute the material herein under the following conditions:
• The copyright and this legal notice must appear in any copies of this document made in whole or in part.
• None of material herein can be sold or otherwise distributed for commercial purposes without written permission of the copyright holder.
• Instructors at any educational institution may freely use this document in their classes as a primary or optional textbook under the conditions specified above.
A local electronic copy of this document may be made under the terms specified for hardcopies: • The copyright and these terms of use must appear in any electronic representation of this document
made in whole or in part.
• None of material herein can be sold or otherwise distributed in an electronic form for commercial purposes without written permission of the copyright holder.
• Instructors at any educational institution may freely store this document in electronic form on a local server as a primary or optional textbook under the conditions specified above.
Additionally, a hardcopy or a local electronic copy must contain the uniform resource locator (URL) providing a link to the original content so the reader can check for updated and corrected content. The current standard URL is http://python.cs.southern.edu/cppbook/html.
1
Chapter 1
The Context of Software Development
A computer program, from one perspective, is a sequence of instructions that dictate the flow of electrical impulses within a computer system. These impulses affect the computer’s memory and interact with the display screen, keyboard, and mouse in such a way as to produce the “magic” that permits humans to perform useful tasks, solve high-level problems, and play games. One program allows a computer to assume the role of a financial calculator, while another transforms the machine into a worthy chess opponent. Note the two extremes here:
• at the lower, more concrete level electrical impulses alter the internal state of the computer, while
• at the higher, more abstract level computer users accomplish real-world work or derive actual plea-sure.
So well is the higher-level illusion achieved that most computer users are oblivious to the lower-level activity (the machinery under the hood, so to speak). Surprisingly, perhaps, most programmers today write software at this higher, more abstract level also. An accomplished computer programmer can develop sophisticated software with little or no interest or knowledge of the actual computer system upon which it runs. Powerful software construction tools hide the lower-level details from programmers, allowing them to solve problems in higher-level terms.
The concepts of computer programming are logical and mathematical in nature. In theory, computer programs can be developed without the use of a computer. Programmers can discuss the viability of a program and reason about its correctness and efficiency by examining abstract symbols that correspond to the features of real-world programming languages but appear in no real-world programming language. While such exercises can be very valuable, in practice computer programmers are not isolated from their machines. Software is written to be used on real computer systems. Computing professionals known as software engineers develop software to drive particular systems. These systems are defined by their underlying hardware and operating system. Developers use concrete tools like compilers, debuggers, and profilers. This chapter examines the context of software development, including computer systems and tools.
1.1. SOFTWARE 2
1.1
Software
A computer program is an example of computer software. Software makes a computer a truly universal machine transforming it into the proper tool for the task at hand. One can refer to a program as a piece of software as if it were a tangible object, but software is actually quite intangible. It is stored on a medium. A hard drive, a CD, a DVD, and a USB pen drive are all examples of media upon which software can reside. The CD is not the software; the software is a pattern on the CD. In order to be used, software must be stored in the computer’s memory. Typically computer programs are loaded into memory from a medium like the computer’s hard disk. An electromagnetic pattern representing the program is stored on the computer’s hard drive. This pattern of electronic symbols must be transferred to the computer’s memory before the program can be executed. The program may have been installed on the hard disk from a CD or from the Internet. In any case, the essence that was transferred from medium to medium was a pattern of electronic symbols that direct the work of the computer system.
These patterns of electronic symbols are best represented as a sequence of zeroes and ones, digits from the binary (base 2) number system. An example of a binary program sequence is
10001011011000010001000001001110
To the underlying computer hardware, specifically the processor, a zero here and three ones there might mean that certain electrical signals should be sent to the graphics device so that it makes a certain part of the display screen red. Unfortunately, only a minuscule number of people in the world would be able to produce, by hand, the complete sequence of zeroes and ones that represent the program Microsoft Word for an Intel-based computer running the Windows 8 operating system. Further, almost none of those who could produce the binary sequence would claim to enjoy the task.
The Word program for older Mac OS X computers using a PowerPC processor works similarly to the Windows version and indeed is produced by the same company, but the program is expressed in a com-pletely different sequence of zeroes and ones! The Intel Core i7 processor in the Windows machine accepts a completely different binary language than the PowerPC processor in the Mac. We say the processors have their own machine language.
1.2
Development Tools
If very few humans can (or want) to speak the machine language of the computers’ processors and software is expressed in this language, how has so much software been developed over the years?
Software can be represented by printed words and symbols that are easier for humans to manage than binary sequences. Tools exist that automatically convert a higher-level description of what is to be done into the required lower-level code. Higher-level programming languages like C++allow programmers to express solutions to programming problems in terms that are much closer to a natural language like English. Some examples of the more popular of the hundreds of higher-level programming languages that have been devised over the past 60 years include FORTRAN, COBOL, Lisp, Haskell, C, Perl, Python, Java, and C#. Most programmers today, especially those concerned with high-level applications, usually do not worry about the details of underlying hardware platform and its machine language.
One might think that ideally such a conversion tool would accept a description in a natural language, such as English, and produce the desired executable code. This is not possible today because natural languages are quite complex compared to computer programming languages. Programs called compilers that translate one computer language into another have been around for over 60 years, but natural language
1.2. DEVELOPMENT TOOLS 3
processing is still an active area of artificial intelligence research. Natural languages, as they are used by most humans, are inherently ambiguous. To understand properly all but a very limited subset of a natural language, a human (or artificially intelligent computer system) requires a vast amount of background knowledge that is beyond the capabilities of today’s software. Fortunately, programming languages provide a relatively simple structure with very strict rules for forming statements that can express a solution to any program that can be solved by a computer.
Consider the following program fragment written in the C++programming language:
subtotal = 25; tax = 3;
total = subtotal + tax;
These three lines do not make up a complete C++ program; they are merely a piece of a program. The statements in this program fragment look similar to expressions in algebra. We see no sequence of bi-nary digits. Three words, subtotal, tax, and total, called variables, are used to hold information. Mathematicians have used variables for hundreds of years before the first digital computer was built. In programming, a variable represents a value stored in the computer’s memory. Familiar operators (= and +) are used instead of some cryptic binary digit sequence that instructs the processor to perform the operation. Since this program is expressed in the C++language, not machine language, it cannot be executed directly on any processor. A C++compiler is used to translate the C++code into machine code.
The higher-level language code is called source code. The compiled machine language code is called the target code. The compiler translates the source code into the target machine language.
The beauty of higher-level languages is this: the same C++source code can be compiled to different target platforms. The target platform must have a C++compiler available. Minor changes in the source code may be required because of architectural differences in the platforms, but the work to move the program from one platform to another is far less than would be necessary if the program for the new platform had to be rewritten by hand in the new machine language. Just as importantly, when writing the program the human programmer is free to think about writing the solution to the problem in C++, not in a specific machine language.
Programmers have a variety of tools available to enhance the software development process. Some common tools include:
• Editors. An editor allows the user to enter the program source code and save it to files. Most pro-gramming editors increase programmer productivity by using colors to highlight language features. The syntax of a language refers to the way pieces of the language are arranged to make well-formed sentences. To illustrate, the sentence
The tall boy runs quickly to the door.
uses proper English syntax. By comparison, the sentence Boy the tall runs door to quickly the.
is not correct syntactically. It uses the same words as the original sentence, but their arrangement does not follow the rules of English.
Similarly, programming languages have strict syntax rules that must be followed to create well-formed programs. Only well-well-formed programs are acceptable and can be compiled and executed. Some syntax-aware editors can use colors or other special annotations to alert programmers of syntax errors before the program is compiled.
1.2. DEVELOPMENT TOOLS 4 Editor #include <io using namespace std; int main() { srand(23); int n; n = rand(); proc(n); #include <io using namespace std; int main() { srand(23); int n; n = rand(); proc(n); 101100010101 000010001100 1100001111010100 0011101101110011 1000000010000110 0111000000111111 1100111011001001 0000100001111000 0001110111101101 1101111011111010 101100010101 000010001100 1100001111010100 0011101101110011 1000000010000110 0111000000111111 1100111011001001 0000100001111000 0001110111101101 1101111011111010 11000011110 00111011011 1000000010000110 0111000000111111 1100111011001001 0000100001111000 0001110111101101 1101111011111010 istream cin; ostream cout; int rand(); void sand(); typedef unsigned U #define NULL (0) Compiler Preprocessor Linker (Design program logic) (Edit) (Preprocess) (Compile) (Link) Source code Library declarations (source code) Enhanced source code Object code Pre-compiled libraries (object code) Executable program Concept of problem solution Programmer’s responsibility Automated by tools
Figure 1.1: Source code to target code sequence
• Compilers. A compiler translates the source code to target code. The target code may be the machine language for a particular platform or embedded device. The target code could be another source language; for example, the earliest C++compiler translated C++into C, another higher-level language. The resulting C code was then processed by a C compiler to produce an executable program. C++ compilers today translate C++directly into machine language.
The complete set of build tools for C++includes a preprocessor, compiler, and linker:
– Preprocessor—adds to or modifies the contents of the source file before the compiler begins processing the code. We use the services of the preprocessor mainly to#includeinformation about library routines our programs use.
– Compiler—translates C++source code to machine code.
– Linker—combines the compiler-generated machine code with precompiled library code or compiled code from other sources to make a complete executable program. Most compiled C++code is incapable of running by itself and needs some additional machine code to make a complete executable program. The missing machine code has been precompiled and stored in a repository of code called a library. A program called a linker combines the programmer’s compiled code and the library code to make a complete program.
1.3. LEARNING PROGRAMMING WITH C++ 5
We generally do not think about the preprocessor, compiler, and linker working as three separate programs (although they do), because the tools we use make it appear as only one process is taking place: translating our source code to an executable program.
• Debuggers. A debugger allows a programmer to more easily trace a program’s execution in order to locate and correct errors in the program’s implementation. With a debugger, a developer can simultaneously run a program and see which line in the source code is responsible for the program’s current actions. The programmer can watch the values of variables and other program elements to see if their values change as expected. Debuggers are valuable for locating errors (also called bugs) and repairing programs that contain errors. (See Section 4.6 for more information about programming errors.)
• Profilers. A profiler collects statistics about a program’s execution allowing developers to tune ap-propriate parts of the program to improve its overall performance. A profiler indicates how many times a portion of a program is executed during a particular run, and how long that portion takes to execute. Profilers also can be used for testing purposes to ensure all the code in a program is actually being used somewhere during testing. This is known as coverage. It is common for software to fail after its release because users exercise some part of the program that was not executed anytime during testing. The main purpose of profiling is to find the parts of a program that can be improved to make the program run faster.
The programming components of the development process are illustrated in Figure 1.1.
Many developers use integrated development environments (IDEs). An IDE includes editors, debug-gers, and other programming aids in one comprehensive program. Examples of IDEs for C++ include Microsoft’s Visual Studio 2012, the Eclipse Foundation’s Eclipse CDT, and Apple’s XCode.
Despite the plethora of tools (and tool vendors’ claims), the programming process for all but trivial programs is not automatic. Good tools are valuable and certainly increase the productivity of developers, but they cannot write software. There are no substitutes for sound logical thinking, creativity, common sense, and, of course, programming experience.
1.3
Learning Programming with C++
Bjarne Stroustrup of AT&T Bell Labs created C++in the mid 1980s. C++is an extension of the programming language C, a product of AT&T Bell Labs from the early 1970s. C was developed to write the Unix operating system, and C is widely used for systems-level software and embedded systems development. C++ initially provided object-oriented programming features (see Chapter 13 and Chapter 14) and later added generic programming capabilities. C++’s close relationship to C allows C++ programs to utilize a large collection of code developed in C.
C++is widely used in industry for commercial software development. It is an industrial strength pro-gramming language used for developing complex systems in business, science, and engineering. Examples of software written in C++include Microsoft Windows 8, Microsoft Office, Mac OS X, and Adobe Creative Suite.
In order to meet the needs of commercial software development and accomplish all that it does, C++ itself is complex. While experienced programmers can accomplish great things with C++, beginners some-times have a difficult time with it. Professional software developers enjoy the flexible design options that C++ permits, but beginners need more structure and fewer options so they can master simpler concepts before moving on to more complex ones.
1.4. SUMMARY 6
This book does not attempt to cover all the facets of the C++ programming language. Experienced programmers should look elsewhere for books that cover C++in much more detail. The focus here is on introducing programming techniques and developing good habits. To that end, our approach avoids some of the more esoteric features of C++and concentrates on the programming basics that transfer directly to other imperative programming languages such as Java, C#, and Python. We stick with the basics and explore more advanced features of C++only when necessary to handle the problem at hand.
1.4
Summary
• Computers require both hardware and software to operate. Software consists of instructions that control the hardware.
• At the lowest level, the instructions for a computer program can be represented as a sequence of zeros and ones. The pattern of zeros and ones determine the instructions performed by the processor. • Two different kinds of processors can have different machine languages.
• Application software can be written largely without regard to the underlying hardware. A tool called a compiler translates the higher-level, abstract language into the machine language required by the hardware.
• Programmers develop software using tools such as editors, compilers, debuggers, and profilers. • C++is a higher-level programming language.
• An IDE is an integrated development environment—one program that provides all the tools that developers need to write software.
1.5
Exercises
1. What is a compiler?2. How is compiled code different from source code?
3. What tool does a programmer use to produce C++source code?
4. What tool(s) does a programmer use to convert C++source code into executable machine code? 5. What does the linker do?
6. Does the linker deal with files containing source code or or machine language code? 7. What does the preprocessor do to source code?
8. List several advantages developing software in a higher-level language has over developing software in machine language.
9. How can an IDE improve a programmer’s productivity?
10. Name a popular C++IDE is used by programmers developing for Microsoft Windows. 11. Name a popular C++IDE is used by programmers developing for Apple Mac OS X.
7
Chapter 2
Writing a C++ Program
Properly written C++ programs have a particular structure. The syntax must be correct, or the compiler will generate error messages and not produce executable machine language. This chapter introduces C++ by providing some simple example programs and associated fundamental concepts. Most of the concepts presented in this chapter are valid in many other programming languages as well. While other languages may implement the concepts using slightly different syntax, the ideas are directly transferable to other languages like C, Java, C#, and Ada.
2.1
General Structure of a Simple C++ Program
Listing 2.1 (simple.cpp) is one of the simplest C++programs that does something:Listing 2.1: simple.cpp 1 #include <iostream> 2 3 using namespace std; 4 5 int main() 6 {
7 cout << "This is a simple C++ program!" << endl;
8 }
The text as shown in Listing 2.1 (simple.cpp) may be typed in an editor and can saved to a file named simple.cpp. The actual name of the file is irrelevant, but the name “simple” accurately describes the nature of this program. The extension.cppis a common extension used for C++source code.
After creating this file with a text editor and compiling it, it prints the message
This is a simple C++ program!
2.1. GENERAL STRUCTURE OF A SIMPLE C++ PROGRAM 8
• #include <iostream>
This line is a preprocessing directive. All preprocessing directives within C++source code begin with a#symbol. This one directs the preprocessor to add some predefined source code to our existing source code before the compiler begins to process it. This process is done automatically and is invisible to us.
Here we want to use some parts of the iostream library, a collection precompiled C++code that can be used by other C++programs (like ours). The iostream library contains routines that handle input and output (I/O) that include functions such as printing to the display, getting user input from the keyboard, and dealing with files.
Two items used in Listing 2.1 (simple.cpp), cout and endl, are not part of the C++language it-self. These items, along with many other things related to input and output, were developed in C++compiled, and stored in the iostream library. The compiler needs to be made aware of these
iostreamitems so it can compile our program. The#includedirective specifies a file, called a header, that contains the specifications for the library code. The compiler checks our code against the specifications in the header to ensure that we are using the library code correctly.
Most of the programs we write use this#include <iostream>directive, and some programs we will write in the future will#includeother information as well.
• using namespace std;
The two items our program needs to display a message on the screen, cout and endl, have longer names: std::cout and std::endl. This using namespace std directive allows us to omit the std:: prefixes and use their shorter names. This directive is optional, but if it is omitted, the longer names must be used. Listing 2.2 (simple2.cpp) shows how the longer names are used. The name std stands for “standard,” and theusing namespace stdline indicates that some of the names we use in our program are part of the so-called “standard namespace.”
• int main()
This specifies the real beginning of our program. Here we are declaring a function named main. All C++programs must contain this function to be executable. Details about the meaning ofintand the parentheses will appear in later chapters. More general information about functions appear in Chapter 8 and Chapter 9.
• {
The open curly brace marks the beginning of the body of a function. The body of a function contains the statements to be carried out when the function executes.
• cout << "This is a simple C++ program!"<< endl;
The body of our main function contains only one statement. This statement causes the message This is a simple C++ program! to be printed on the screen. A statement is the fundamental unit of execution in a C++program. Functions contain statements that are compiled into executable code. C++has a variety of different kinds of statements, and the chapters that follow explore these various kinds of statements. All statements in C++end with a semicolon (;). A more detailed explanation of this statement appears below.
• }
The close curly brace marks the end of the body of a function. Both the open curly brace and close curly brace are required for every function definition.
2.2. COMPILING THE SOURCE CODE 9
Note which lines in the program end with a semicolon (;) and which do not. Do not put a semicolon after the #includepreprocessor directive. Do not put a semicolon on the line containing main, and do not put semicolons after the curly braces.
2.2
Compiling the source code
C++ compilers come in a variety of forms. Some, such as Microsoft’s Visual Studio 2012 and Apple’s XCode tools provide IDEs (see Section 1.2) with many features. In this section we focus on building C++programs with Microsoft’s Visual Studio 2012. The Visual C++Express Edition, which is more than adequate for building and running the programs in this text, is available as a free download from Microsoft’s VisualC++Express website at http://www.microsoft.com/express/vc. More information about Visual Studio 2012 can be found at Microsoft’s Visual Studio website, http://msdn.microsoft.com/en-us/ vstudio/default.aspx.
While we will be concentrating on Visual C++, the code in this text is not Visual C++specific. The code herein aims to be C++standards compliant and platform independent.
The following describes the task of C++software development under Visual Studio:
• To begin creating a C++program, you must first launch Visual Studio 2012 from the Start menu or other relevant shortcut. Figure 2.1 shows the start menu of a typical Windows 7 system and the Visual Studio application tile in Windows 8. You quickly should see a splash screen similar to the one shown
Figure 2.1: Launching Visual Studio from the Windows 7 start menu or Windows 8 application tile and the ensuing .
in Figure 2.1.
2.2. COMPILING THE SOURCE CODE 10
configures the development environment for you. At this point you will indicate that Visual C++is your preferred development language (not necessary if you are using the Visual C++Express Edition). Figure 2.2 shows what Visual Studio looks like when it is fully loaded and ready to use.
Figure 2.2: Visual Studio Ready for Use
• After Visual Studio has started, you begin the process of developing a C++ program by creating a new project. As Figure 2.3 shows, you can create a new project by following the menu sequence: File→New→Project
Figure 2.3: Creating a New Project
• In the dialog that results, shown on the right of Figure 2.3, you should choose the project type to be Visual C++in the left pane, and use the Win32 Console Application option in the center pane. In the name field near the bottom of the dialog, enter a name for the project; we will use the name simple. You may change the location to a different folder if you like, or even a different drive (such as a USB pen drive). In this example, we chose to not change the default location provided by Visual Studio. • When you select OK on the project creation dialog, a Win32 Application Wizard as shown on the left
of Figure 2.4 appears. At this point, the instructions in the dialog say “Click Finish from any window to accept the current settings.” Do not select Finish; instead, select Next to continue. We have one more key step to complete so our project is set up correctly.
2.2. COMPILING THE SOURCE CODE 11
Figure 2.4: Configuring the New Project
• In the subsequent Applications Settings dialog (see the right image in Figure 2.4), select the em-phEmpty project checkbox. Also, uncheck the Security Development Lifecycle box. The dialog should look like the right image in Figure 2.4 before you proceed. Choose Finish when you are ready to continue.
• At this point, the Solution Explorer panel shows the structure of the newly created, albeit empty, project. The left image in Figure 2.5 shows the newly populated Solution Explorer pane.
Figure 2.5: Adding a C++ Source File
• Right click on the simple element in the Solution Explorer. As shown on the right of in Figure 2.5, select Add and New Item from the resulting pop-up menu.
• In the Add New Item dialog box, shown on the left in Figure 2.6, select C++File (.cpp)˜ and enter a name for the C++file in the text field at the bottom. You need not add .cpp to the end of the name, as Visual Studio will do that for you. The file here will be namedsimple.cpp. Press Add when done. • As shown on the right in Figure 2.6, the Solution Explorer pane now shows the file simple.cpp,
and the large editor pane is ready for you to type in the source code for the program. The new source file is initially empty.
• In the editor pane with the simple.cpp tab at the top, type in the source code for our simple C++ program. Figure 2.7 shows the completed code.
2.2. COMPILING THE SOURCE CODE 12
Figure 2.6: Ready to Edit the C++ Source File
Figure 2.7: Editor Pane
• You may save the source file at this point by selecting Save from the File menu or by pressing pressing at the same time the Ctrl S keys. If you do not save your program, Visual Studio will prompt you to do so before it builds and runs your program.
To run the program, select Debug→Start Without Debugging, as shown on the left of Figure 2.8. Visual Studio will attempt to build the executable program. It will prompt you to save your file if you
Figure 2.8: Building and Running the Program
have not saved it or have made changes since the last time you saved it. The progress of the build process is displayed is in the Output panel in the bottom window. One of the lines has
1>Compiling. . . and another later has
2.2. COMPILING THE SOURCE CODE 13
1>Linking. . .
The last few lines are very important: 1>Build succeeded.
1>
1>Time Elapsed 00:00:02.98
========= Build: 1 succeeded, 0 failed, 0 up-to-date, 0 skipped ========== These lines indicate the build was successful.
• A console window appears with the output of your program. The right image in Figure 2.8 shows this text window. You can press any key on the keyboard to close the window. If the console window does not appear, you have typographical errors in your program; return to the editor, fix the errors, and try to run the program again.
• When you are finished with Visual Studio, select the File→Exit menu items as shown in Figure 2.9.
Figure 2.9: Exiting Visual Studio
These are the steps for writing a basic C++program in Visual Studio 2012. While the steps initially may seem complex and tedious, they will become natural after you have written a few C++programs.
When the program was run, the Visual Studio environment created a console window in which to run the program.
This is a simple C++ program! Press any key to continue . . .
The first line of the output was printed by the program. The second line prompting the user to press any key to continue is added by the Visual C++run-time environment so the console window stays visible long enough for the user to see the output. If you run the program from a the standard Windows command shell (CMD.EXE, usually found in the Start menu under Accessories and named Command Prompt), only the program’s output will appear and the “Press any key to continue . . .” message will not appear.
The following summarizes the steps you should follow when writing a C++program using the Visual Studio IDE:
2.3. VARIATIONS OF OUR SIMPLE PROGRAM 14
1. In the main menu:
File→New→Project (or Ctrl Shift N )
2. Select “Win32 Console Project” and click “Next” to set the “Empty Project” option 3. In the Solution Explorer pane right click on “Source Files” and select
Add→New Item...
4. Select C++File (.cpp) and enter the name of your file 5. Type in the source code for your program in the editor panel 6. Save your file:
File→Save filename (or Ctrl S )
7. In the main menu:
Debug→Start Without Debugging (or Ctrl F5 )
It is possible to develop C++programs without using Visual Studio’s integrated development environ-ment. Visual Studio comes with some additional tools for command-line developenviron-ment. Appendix A de-scribes how you can edit the C++source code with a standalone text editor and compile and run the program from the Windows command prompt (CMD.EXE). Command-line development under Linux and Mac OS X is covered in B. Some programmers prefer the freedom of using their favorite editor, and the standalone tools can be used in scripts to automate the build process.
2.3
Variations of our simple program
The two items Listing 2.1 (simple.cpp) needed to display a message on the screen, cout and endl, have longer names: std::cout and std::endl. The using namespace std directive allows us to omit the std:: prefixes and use their shorter names. This directive is optional, but if it is omitted, the longer names must be used. For example, Listing 2.2 (simple2.cpp) shows an alternative way of writing Listing 2.1 (simple.cpp). Listing 2.2: simple2.cpp 1 #include <iostream> 2 3 int main() 4 {
5 std::cout << "This is a simple C++ program!" << std::endl;
6 }
Listing 2.3 (simple3.cpp) shows another way to use the shorter names for cout and endl within a C++ program. Listing 2.3: simple3.cpp 1 #include <iostream> 2 3 using std::cout; 4 using std::endl; 5
2.3. VARIATIONS OF OUR SIMPLE PROGRAM 15
6 int main()
7 {
8 cout << "This is a simple C++ program!" << endl;
9 }
We generally will not use the third approach, although you will encounter it in published C++code. The compiler will generate the same machine language code for all three versions. We generally will write programs that use theusing namespacedirective and, therefore, use the shorter names.
The statement in the main function in any of the three versions of our program uses the services of an object called std::cout. The std::cout object prints text on the computer’s screen. The text of the message as it appears in the C++source code is called a string, for string of characters. Strings are enclosed within quotation marks (”). The symbols << make up the insertion operator. You can think of the message to be printed as being “inserted” into the cout object. The cout object represents the output stream; that is, text that the program prints to the console window. The endl word means “the end of line of printed text,” and it causes the cursor to move down to the next line so any subsequent output will appear on the next line. If you read the statement from left to right, the cout object which is responsible for displaying text on the screen first receives the text to print and then receives the end-of-line directive to move to the next line.
For simplicity, we’ll refer to this type of statement as a print statement, even though the word print does not appear anywhere in the statement.
With minor exceptions, any statement in C++must appear within a function definition. Our single print statement appears within the function named main.
Any function, including main, may contain multiple statements. In Listing 2.4 (arrow.cpp), six print statements draw an arrow on the screen:
Listing 2.4: arrow.cpp 1 #include <iostream> 2 3 using namespace std; 4 5 int main() 6 { 7 cout << " * " << endl; 8 cout << " *** " << endl; 9 cout << " ***** " << endl; 10 cout << " * " << endl; 11 cout << " * " << endl; 12 cout << " * " << endl; 13 }
The output of Listing 2.4 (arrow.cpp) is
* *** ***** * * *
2.3. VARIATIONS OF OUR SIMPLE PROGRAM 16
Each print statement “draws” a horizontal slice of the arrow. The six statements
cout << " * " << endl; cout << " *** " << endl; cout << " ***** " << endl; cout << " * " << endl; cout << " * " << endl; cout << " * " << endl;
constitute the body of the main function. The body consists of all the statements between the open curly brace () and close curly brace (). We say that the curly braces delimit the body of the function.
Listing 2.4 (arrow.cpp) can be rewritten to achieve the same effect with only one long print statement as shown in Listing 2.5 (arrow2.cpp).
Listing 2.5: arrow2.cpp 1 2 #include <iostream> 3 4 using namespace std; 5 6 int main() 7 { 8 cout << " * " << endl 9 << " *** " << endl 10 << " ***** " << endl 11 << " * " << endl 12 << " * " << endl 13 << " * " << endl; 14 }
At first, Listing 2.4 (arrow.cpp) and Listing 2.5 (arrow2.cpp) may appear to be identical, but upon closer inspection we see that cout appears only once within main, and only one semicolon (;) appears within
main. Since semicolons in C++ terminate statements, there really is only one statement. Notice that a single statement can be spread out over several lines. The statement within main appearing as
cout << " * " << endl << " *** " << endl << " ***** " << endl << " * " << endl << " * " << endl << " * " << endl;
could have just as easily been written as
cout << " * " << endl << " *** "
<< endl << " ***** " << endl << " * " << endl
<< " * " << endl << " * " << endl;
but the first way of expressing it better portrays how the output will appear. Read this second version carefully to convince yourself that the printed pieces will indeed flow to the cout printing object in the proper sequence to produce the same picture of the arrow.
2.4. TEMPLATE FOR SIMPLE C++ PROGRAMS 17
Consider the mistake of putting semicolons at the end of each of the lines in the “one statement” version:
cout << " * " << endl; << " *** " << endl; << " ***** " << endl; << " * " << endl; << " * " << endl; << " * " << endl;
If this code fragment is put in main, the program will not compile. The reason is simple—the semicolon at the end of the first line terminates the statement on that line. The compiler expects a new statement on the next line, but
<< " *** " << endl;
is not a complete legal C++statement since the << operator is missing the cout object. The string" *** "and the end-of-line marker has nothing to “flow into.”
Listing 2.6 (empty.cpp) is even simpler than Listing 2.1 (simple.cpp).
Listing 2.6: empty.cpp
1
2 int main()
3 {
4 }
Since Listing 2.6 (empty.cpp) uses neither the cout object nor endl, the#includeandusing direc-tives are not needed. While it is legal and sometimes even useful in C++ to write functions with empty bodies, such functions will do nothing when they execute. Listing 2.6 (empty.cpp) with its empty main function is, therefore, truly the simplest executable C++ program that can be written, but it does nothing when it runs!
In general, a C++program may contain multiple functions, but such generality is deferred until Chap-ter 9. For now, we will restrict our attention to programs with only a main function.
2.4
Template for simple C++ programs
For our immediate purposes all the programs we write will have the form shown in Figure 2.10.
Our programs generally will print something, so we need the#includedirective. Since we will use the short names for the printing objects, we also include theusing namespacedirective. The main function definition is required for an executable program, and we will fill its body with statements that make our program do as we wish. Later, our programs will become more sophisticated, and we will augment this simple template.
2.5. SUMMARY 18
program statements
#include <iostream>
using namespace std;
int main()
{
}
Figure 2.10: The general structure of a C++program.
2.5
Summary
• Any programs that print to the screen must use the#includedirective to so that the program can make use of the precompiled iostream library code to do I/O (input and output).
• All preprocessor directives begin with the#symbol.
• Messages can be printed on the screen by sending them to the std::cout object using the << operator.
• The << operator used in conjunction with the cout stream object is known as the insertion operator. • The end of a printed line is signified by sending std::endl to the std::cout object.
• The shorter names cout and endl can be used if theusing namespace stdappears at the top of the program’s source code.
• An executable C++program must contain a function named main.
• Functions contain statements that are executed by the computer when the program runs. (The program must be compiled for the computer to be able to execute the statements.)
• A function’s body consists of all the statements inside the delimiting curly braces ({}).
• A function’s body may be empty; however, such a function performs no useful activity when it executes.
• Statements are terminated with semicolons (;).
• Within the Visual Studio IDE a program is developed within a project.
• Visual Studio’s command prompt environment can be used to develop simple C++programs without the overhead of creating a project.
2.6. EXERCISES 19
2.6
Exercises
1. What preprocessor directive must be used to allow statements to use the std::cout printing stream?
2. What statement allows the short names cout and endl to be used instead of std::cout and
std::endl?
3. What does the name std stand for?
4. All C++programs must have a function named what? 5. The body of main is enclosed within what symbols?
6. What operator directs information to the std::cout output stream? 7. Write a C++program that prints your name in the console window.
8. Write a C++program that prints your first and last name in the console window. Your first name should appear on one line, and your last name appear on the next line.
9. What other files must be distributed with your executable file so that your program will run on a Windows PC without Visual Studio installed? window.
21
Chapter 3
Values and Variables
In this chapter we explore some building blocks that are used to develop C++ programs. We experiment with the following concepts:
• numeric values • variables • declarations • assignment • identifiers • reserved words
In the next chapter we will revisit some of these concepts in the context of other data types.
3.1
Integer Values
The number four (4) is an example of a numeric value. In mathematics, 4 is an integer value. Integers are whole numbers, which means they have no fractional parts, and they can be positive and negative. Examples of integers include 4, −19, 0, and −1005. In contrast, 4.5 is not an integer, since it is not a whole number.
C++supports a number of numeric and non-numeric values. In particular, C++programs can use integer values. It is easy to write a C++program that prints the number four, as Listing 3.1 (number4.cpp) shows.
Listing 3.1: number4.cpp 1 #include <iostream> 2 3 using namespace std; 4 5 int main() 6 { 7 cout << 4 << endl; 8 }
3.1. INTEGER VALUES 22
Notice that unlike the programs we saw earlier, Listing 3.1 (number4.cpp) does not use quotation marks ("). Compare Listing 3.1 (number4.cpp) to Listing 3.2 (number4-alt.cpp).
Listing 3.2: number4-alt.cpp 1 #include <iostream> 2 3 using namespace std; 4 5 int main() 6 { 7 cout << "4" << endl; 8 }
Both programs behave identically, but Listing 3.1 (number4.cpp) prints the value of the number four, while Listing 3.2 (number4-alt.cpp) prints a message containing the digit four. The distinction here seems unim-portant, but we will see in Section 3.2 that the presence or absence of the quotes can make a big difference in the output.
In C++ source code, integers are not written with commas. The number two thousand, four hundred sixty-eight would be written 2468, not 2,468. In mathematics, integers are unbounded; said another way, the set of mathematical integers is infinite. In C++the range of integers is limited, because all computers have a finite amount of memory. The exact range of integers supported depends on the computer system and particular C++ compiler. C++ on most 32-bit computer systems can represent integers in the range −2,147,483,648 to +2,147,483,647.
What happens if you exceed the range of C++integers? Try Listing 3.3 (exceed.cpp) on your system.
Listing 3.3: exceed.cpp 1 #include <iostream> 2 3 using namespace std; 4 5 int main() 6 { 7 cout << -3000000000 << endl; 8 }
Negative three billion is too large for 32-bit integers, however, and the program’s output is obviously wrong:
1294967296
The number printed was not even negative! (The Visual C++ compiler does issue a warning, but it still produces the executable program.)
This limited range of values is common among programming languages since each number is stored in a fixed amount of memory. Larger numbers require more storage in memory. In order to model the infinite set of mathematical integers an infinite amount of memory would be needed! As we will see later, C++ supports an integer type with a greater range.
3.2. VARIABLES AND ASSIGNMENT 23
3.2
Variables and Assignment
In algebra, variables are used to represent numbers. The same is true in C++, except C++variables also can represent values other than numbers. Listing 3.4 (variable.cpp) uses a variable to store an integer value and then prints the value of the variable.
Listing 3.4: variable.cpp 1 #include <iostream> 2 3 using namespace std; 4 5 int main() 6 { 7 int x; 8 x = 10; 9 cout << x << endl; 10 }
The main function in Listing 3.4 (variable.cpp) contains three statements: • int x;
This is a declaration statement. All variables in a C++ program must be declared. A declaration specifies the type of a variable. The word intindicates that the variable is an integer. The name of the integer variable is x. We say that variable x has typeint. C++ supports types other than integers, and some types require more or less space in the computer’s memory. The compiler uses the declaration to reserve the proper amount a memory to store the variable’s value. Due to the declaration the compiler also can check to see if the variable is being used properly; for example, we will see that integers can be added together just like in mathematics. For some other data types, however, addition is not possible and so is not allowed. The compiler can ensure that a variable involved in an addition is compatible with addition. It can report an error if it is not.
The compiler will issue an error if a programmer attempts to use an undeclared variable. The com-piler cannot deduce the storage requirements and cannot verify the variable’s proper usage if it not declared. Once declared, a particular variable cannot be redeclared in the same context. A variable may not change its type during its lifetime.
• x = 10;
This is an assignment statement. An assignment statement associates a value with a variable. The key to an assignment statement is the symbol = which is known as the assignment operator. Here the value 10 is being assigned to the variable x. This means the value 10 will be stored in the memory location the compiler has reserved for the variable named x. We need not be concerned about where the variable is stored in memory; the compiler takes care of that detail.
After it has been declared, a variable may be assigned and reassigned as often as necessary. • cout << x << endl;
3.2. VARIABLES AND ASSIGNMENT 24
Note that the lack of quotation marks here is very important. If x has the value 10, the statement
cout << x << endl;
prints 10, the value of the variable x, but the statement
cout << "x" << endl;
prints x, the message containing the single letter x.
The meaning of the assignment operator (=) is different from equality in mathematics. In mathematics,
=asserts that the expression on its left is equal to the expression on its right. In C++, = makes the variable on its left take on the value of the expression on its right. It is best to read x = 5 as “x is assigned the value 5,” or “x gets the value 5.” This distinction is important since in mathematics equality is symmetric: if x = 5, we know 5 = x. In C++, this symmetry does not exist; the statement
5 = x;
attempts to reassign the value of the literal integer value 5, but this cannot be done because 5 is always 5 and cannot be changed. Such a statement will produce a compiler error:
error C2106: ’=’ : left operand must be l-value
Variables can be reassigned different values as needed, as Listing 3.5 (multipleassignment.cpp) shows.
Listing 3.5: multipleassignment.cpp 1 #include <iostream> 2 3 using namespace std; 4 5 int main() 6 { 7 int x; 8 x = 10; 9 cout << x << endl; 10 x = 20; 11 cout << x << endl; 12 x = 30; 13 cout << x << endl; 14 }
Observe the each print statement in Listing 3.5 (multipleassignment.cpp) is identical, but when the program runs the print statements produce different results.
A variable may be given a value at the time of its declaration; for example, Listing 3.6 (variable-init.cpp) is a variation of Listing 3.4 (variable.cpp).
Listing 3.6: variable-init.cpp
1 #include <iostream> 2
3.2. VARIABLES AND ASSIGNMENT 25 4 5 int main() 6 { 7 int x = 10; 8 cout << x << endl; 9 }
Notice that in Listing 3.6 (variable-init.cpp) the declaration and assignment of the variable x is performed in one statement instead of two. This combined declaration and immediate assignment is called initialization.
C++supports another syntax for initializing variables as shown in Listing 3.7 (alt-variable-init.cpp).
Listing 3.7: alt-variable-init.cpp 1 #include <iostream> 2 3 using namespace std; 4 5 int main() 6 { 7 int x(10); 8 cout << x << endl; 9 }
This alternate form is not commonly used for simple variables, but it necessary for initializing more com-plicated kinds of variables called objects. Objects are introduced in Chapter 13 and Chapter 14.
Multiple variables of the same type can be declared and, if desired, initialized in a single statement. The following statements declare three variables in one declaration statement:
int x, y, z;
The following statement declares three integer variables and initializes two of them: int x = 0, y, z = 5;
Here y’s value is undefined.
The compiler maps a variable to a location in the computer’s memory. We can visualize a variable and its corresponding memory location as a box as shown in Figure 3.1.
5
a
Figure 3.1: Representing a variable and its memory location as a box
We name the box with the variable’s name. Figure 3.2 shows how the following sequence of C++code affects memory.
3.3. IDENTIFIERS 26 int a, b; a = 2; b = 5; a = b; b = 4;
?
?
a
b
int a, b;
2
?
a
b
a = 2;
2
5
a
b
b = 5;
5
5
a
b
a = b;
5
4
a
b
b = 4;
Figure 3.2: How memory changes during variable assignment Importantly, the statement
a = b;
does not mean a and b refer to the same box (memory location). After this statement a and b still refer to separate boxes (memory locations). It simply means the value stored in b’s box (memory location) has been copied to a’s box (memory location). a and b remain distinct boxes (memory locations). The original value found in a’s box is overwritten when the contents of b’s box are copied into a. After the assignment of b to a, the reassignment of b to 4 does not affect a.
3.3
Identifiers
While mathematicians are content with giving their variables one-letter names like x, programmers should use longer, more descriptive variable names. Names such as sum, height, and subTotal are much better than the equally permissible s, h, and st. A variable’s name should be related to its purpose within the program. Good variable names make programs more readable by humans. Since programs often contain
3.3. IDENTIFIERS 27
many variables, well-chosen variable names can render an otherwise obscure collection of symbols more understandable.
C++has strict rules for variable names. A variable name is one example of an identifier. An identifier is a word used to name things. One of the things an identifier can name is a variable. We will see in later chapters that identifiers name other things such as functions and classes. Identifiers have the following form:
• Identifiers must contain at least one character.
• The first character must be an alphabetic letter (upper or lower case) or the underscore
ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz_
• The remaining characters (if any) may be alphabetic characters (upper or lower case), the underscore, or a digit
ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz_0123456789
• No other characters (including spaces) are permitted in identifiers. • A reserved word cannot be used as an identifier (see Table 3.1). Here are some examples of valid and invalid identifiers:
• All of the following words are valid identifiers and so can be used as variable names: x, x2, total,
port_22, and FLAG.
• None of the following words are valid identifiers: sub-total (dash is not a legal symbol in an identifier), first entry (space is not a legal symbol in an identifier), 4all (begins with a digit), #2(pound sign is not a legal symbol in an identifier), andclass(classis a reserved word). C++ reserves a number of words for special use that could otherwise be used as identifiers. Called reserved wordsor keywords, these words are special and are used to define the structure of C++programs and statements. Table 3.1 lists all the C++reserved words.
The purposes of many of these reserved words are revealed throughout this book.
None of the reserved words in Table 3.1 can be used as identifiers. Fortunately, if you accidentally attempt to use one of the reserved words in a program as a variable name, the compiler will issue an error (see Section 4.6 for more on compiler errors).
In Listing 2.1 (simple.cpp) we used several reserved words: using,namespace, andint. Notice that include, cout, endl, and main are not reserved words.
While mathematicians are content with giving their variables one-letter names like x, programmers should use longer, more descriptive variable names. Names such as sum, height, and sub_total are much better than the equally permissible s, h, and st. A variable’s name should be related to its purpose within the program. Good variable names make programs more readable by humans. Since programs often contain many variables, well-chosen variable names can render an otherwise obscure collection of symbols more understandable.
Some programming languages do not require programmers to declare variables before they are used; the type of a variable is determined by how the variable is used. Some languages allow the same variable to assume different types as its use differs in different parts of a program. Such languages are known as dynamically-typed languages. C++is a statically-typed language. In a statically-typed language, the type of
3.3. IDENTIFIERS 28
alignas alignof and and_eq
asm auto bitand bitor
bool break case catch
char char16_t char32_t class
compl const constexpr const_cast
continue decltype default delete
do double dynamic_cast else
enum explicit export extern
false float for friend
goto if inline int
long mutable namespace new
noexcept not not_eq nullptr
operator or or_eq private
protected public register reinterpret_cast
return short signed sizeof
static static_assert static_cast struct
switch template this thread_local
throw true try typedef
typeid typename union unsigned
using virtual void volatile
wchar_t while xor xor_eq
Table 3.1: C++keywords
a variable must be explicitly specified before it is used by statements in a program. While the requirement to declare all variables may initially seem like a minor annoyance, it offers several advantages:
• When variables must be declared, the compiler can catch typographical errors that dynamically-typed languages cannot detect. For example, consider the following section of code:
int ZERO; ZER0 = 1;
The identifier in the first line ends with a capital “Oh.” In the second line, the identifier ends with the digit zero. The distinction may be difficult or impossible to see in a particular editor or printout of the code. A C++compiler would immediately detect the typo in the second statement, since ZER0 (last letter a zero) has not been declared. A dynamically-typed language would create two variables:
ZEROand ZER0.
• When variables must be declared, the compiler can catch invalid operations. For example, a variable may be declared to be of type int, but the programmer may accidentally assign a non-numeric value to the variable. In a dynamically-typed language, the variable would silently change its type introducing an error into the program. In C++, the compiler would report the improper assignment as error, since once declared a C++variable cannot change its type.
• Ideally, requiring the programmer to declare variables forces the programmer to plan ahead and think more carefully about the variables a program might require. The purpose of a variable is tied to its type, so the programmer must have a clear notion of the variable’s purpose before declaring it. When variable declarations are not required, a programmer can “make up” variables as needed as the code is written. The programmer need not do the simple double check of the variable’s purpose that writing
3.4. FLOATING-POINT TYPES 29
Type Storage Smallest Magnitude Largest Magnitude Minimum Precision
float 4 bytes 1.17549 × 10−38 3.40282 × 10+38 6 digits double 8 bytes 2.22507 × 10−308 1.79769 × 10+308 15 digits
Table 3.2: Characteristics of Floating-point Numbers on 32-bit Computer Systems
the variable’s declaration requires. While declaring the type of a variable specifies its purpose in only a very limited way, any opportunity to catch such errors is beneficial.
• Statically-typed languages are generally more efficient than dynamically-typed languages. The com-piler knows how much storage a variable requires based on its type. The space for that variable’s value will not change over the life of the variable, since its type cannot change. In a dynamically typed language that allows a variable to change its type, if a variable’s type changes during program execution, the storage it requires may change also, so memory for that variable must be allocated elsewhere to hold the different type. This memory reallocation at run time slows down the program’s execution.
C++is a case-sensitive language. This means that capitalization matters. ifis a reserved word, but none of If, IF, or iF are reserved words. Identifiers are case sensitive also; the variable called Name is different from the variable called name.
Variable names should not be distinguished merely by differences in capitalization because it can be confusing to human readers. For the same reason, it is considered poor practice to give a variable the same name as a reserved word with one or more of its letters capitalized.
3.4
Floating-point Types
Many computational tasks require numbers that have fractional parts. For example, to compute the area of a circle given the circle’s radius, the value π, or approximately 3.14159 is used. C++supports such non-integer numbers, and they are called floating-point numbers. The name implies that during mathematical calculations the decimal point can move or “float” to various positions within the number to maintain the proper number of significant digits. The typesfloatanddoublerepresent different types of floating-point numbers. The typedoubleis used more often, since it stands for “double-precision floating-point,” and it can represent a wider range of values with more digits of precision. Thefloattype represents single-precision floating-point values that are less precise. Table 3.2 provides some information about floating-point values as commonly implemented on 32-bit computer systems. Floating point numbers can be both positive and negative.
As you can see from Table 3.2,doubles provide more precision at the cost of using more memory. Listing 3.8 (pi-print.cpp) prints an approximation of the mathematical value π.
Listing 3.8: pi-print.cpp 1 #include <iostream> 2 3 using namespace std; 4 5 int main() 6 { 7 double pi = 3.14159;