Docsity

Programming Abstractions in C++, Study notes of Programming Abstractions

Toggle sidebar
bg1
Programming
Abstractions in C++
Eric S. Roberts and Julie Zelenski
This course reader has had an interesting evolutionary history that in some ways mirrors
the genesis of the C++ language itself. Just as Bjarne Stroustup’s first version of C++
was implemented on top of a C language base, this reader began its life as Eric Roberts’s
textbook Programming Abstractions in C (Addison-Wesley, 1998). In 2002-03, Julie
Zelenski updated it for use with the C++ programming language, which we began using
in CS106B and CS106X during that year.
Although the revised text worked fairly well at the outset, CS106B and CS106X have
evolved in recent years so that their structure no longer tracks the organization of the
book. This year, we’re engaged in the process of rewriting the book so that students in
these courses can use it as both a tutorial and a reference. As always, that process takes a
considerable amount to time, and there are likely to be some problems as we update the
reader. At the same time, we’re convinced that the material in CS106B and CS106X is
tremendously exciting and will be able to carry us through a quarter or two of instability,
and we will end up with an even better course in the future.
We want to thank our colleagues at Stanford, several generations of section leaders (with
special thanks to Dan Bentley and Keith Schwarz), and so many students over the
years—all of whom have helped make it so exciting to teach this wonderful material.
pf3
pf4
pf5
pf8
pf9
pfa
pfd
pfe
pff
pf12
pf13
pf14
pf15
pf16
pf17
pf18
pf19
pf1a
pf1b
pf1c
pf1d
pf1e
pf1f
pf20
pf21
pf22
pf23
pf24
pf25
pf26
pf27
pf28
pf29
pf2a
pf2b
pf2c
pf2d
pf2e
pf2f
pf30
pf31
pf32
pf33
pf34
pf35
pf36
pf37
pf38
pf39
pf3a
pf3b
pf3c
pf3d
pf3e
pf3f
pf40
pf41
pf42
pf43
pf44
pf45
pf46
pf47
pf48
pf49
pf4a
pf4b
pf4c
pf4d
pf4e
pf4f
pf50
pf51
pf52
pf53
pf54
pf55
pf56
pf57
pf58
pf59
pf5a
pf5b
pf5c
pf5d
pf5e
pf5f
pf60
pf61
pf62
pf63
pf64

Partial preview of the text

Download Programming Abstractions in C++ and more Study notes Programming Abstractions in PDF only on Docsity!

Programming

Abstractions in C++

Eric S. Roberts and Julie Zelenski

This course reader has had an interesting evolutionary history that in some ways mirrors the genesis of the C++ language itself. Just as Bjarne Stroustup’s first version of C++ was implemented on top of a C language base, this reader began its life as Eric Roberts’s textbook Programming Abstractions in C (Addison-Wesley, 1998). In 2002-03, Julie Zelenski updated it for use with the C++ programming language, which we began using in CS106B and CS106X during that year.

Although the revised text worked fairly well at the outset, CS106B and CS106X have evolved in recent years so that their structure no longer tracks the organization of the book. This year, we’re engaged in the process of rewriting the book so that students in these courses can use it as both a tutorial and a reference. As always, that process takes a considerable amount to time, and there are likely to be some problems as we update the reader. At the same time, we’re convinced that the material in CS106B and CS106X is tremendously exciting and will be able to carry us through a quarter or two of instability, and we will end up with an even better course in the future.

We want to thank our colleagues at Stanford, several generations of section leaders (with special thanks to Dan Bentley and Keith Schwarz), and so many students over the years—all of whom have helped make it so exciting to teach this wonderful material.

ii

Programming Abstractions in C++

Chapter 1. An Overview of C++ 1

1.1 What is C++? 2 The object-oriented paradigm; The compilation process

1.2 The structure of a C++ program 5 Comments; Library inclusions; Program-level definitions; Function prototypes; The main program; Function definitions

1.3 Variables, values, and types 9 Naming conventions; Local and global variables; The concept of a data type; Integer types; Floating-point types; Text types; Boolean type; Simple input and output

1.4 Expressions 16 Precedence and associativity; Mixing types in an expression; Integer division and the remainder operator; Type casts; The assignment operator; Increment and decrement operators; Boolean operators

1.5 Statements 24 Simple statements; Blocks; The if statement; The switch statement; The while statement; The for statement

1.6 Functions 32 Returning results from functions; Function definitions and prototypes; The mechanics of the function-calling process; Passing parameters by reference

Summary 38 Review questions 39 Programming exercises 41

Chapter 2. Data Types in C++ 45

2.1 Enumeration types 46 Internal representation of enumeration types; Scalar types

2.2 Data and memory 49 Bits; bytes; and words; Memory addresses

2.3 Pointers 51 Using addresses as data values; Declaring pointer variables; The fundamental pointer operations

2.4 Arrays 56 Array declaration; Array selection; Effective and allocated sizes; Initialization of arrays; Multidimensional arrays

2.5 Pointers and arrays 64 The relationship between pointers and arrays

2.6 Records 67 Defining a new structure type; Declaring structure variables; Record selection; Initializing records; Pointers to records

2.7 Dynamic allocation 71 Coping with memory limitations; Dynamic arrays; Dynamic records

iv

Summary 163 Review questions 164 Programming exercises 165

Chapter 5. Introduction to recursion 173

5.1 A simple example of recursion 174

5.2 The factorial function 176 The recursive formulation of Fact ; Tracing the recursive process; The recursive leap of faith

5.3 The Fibonacci function 181 Computing terms in the Fibonacci sequence; Gaining confidence in the recursive implementation; Recursion is not to blame

5.4 Other examples of recursion 187 Detecting palindromes; Binary search; Mutual recursion

5.5 Thinking recursively 192 Maintaining a holistic perspective; Avoiding the common pitfalls

Summary 194 Review questions 195 Programming exercises 197

Chapter 6. Recursive procedures 201

6.1 The Tower of Hanoi 202 Framing the problem; Finding a recursive strategy; Validating the strategy; Coding the solution; Tracing the recursive process

6.2 Generating permutations 211 The recursive insight

6.3 Graphical applications of recursion 213 The graphics library; An example from computer art; Fractals

Summary 224 Review questions 225 Programming exercises 226

Chapter 7. Backtracking algorithms 235

7.1 Solving a maze by recursive backtracking 236 The right-hand rule; Finding a recursive approach; Identifying the simple cases; Coding the maze solution algorithm; Convincing yourself that the solution works

7.2 Backtracking and games 245 The game of nim; A generalized program for two-player games; The minimax strategy; Implementing the minimax algorithm; Using the general strategy to solve a specific game

Summary 269 Review questions 270 Programming exercises 271

v

Chapter 8. Algorithmic analysis 277

8.1 The sorting problem 278 The selection sort algorithm; Empirical measurements of performance; Analyzing the performance of selection sort

8.2 Computational complexity and big-O notation 282 Big-O notation; Standard simplifications of big-O; Predicting computational complexity from code structure; Worst-case versus average-case complexity; A formal definition of big-O

8.3 Recursion to the rescue 288 The power of divide-and-conquer strategies; Merging two vectors; The merge sort algorithm; The computational complexity of merge sort; Comparing N^2 and N log N performance

8.4 Standard complexity classes 294

8.5 The Quicksort algorithm 296 Partitioning the vector; Analyzing the performance of Quicksort

8.6 Mathematical induction 301

Summary 304 Review questions 305 Programming exercises 307

Chapter 9. Classes and objects 313

9.1 A simple example of a class definition 314 Defining a Point class; Implementing methods in a class; Constructors and destructors; The keyword this

9.2 Implementing a specialized version of the Stack class 319 Defining the CharStack interface; Representing the stack data; The advantages of object encapsulation; Removing the maximum size limitation; Object copying

9.3 Implementing the Scanner class 328

Summary 328 Review questions 334 Programming exercises 335

Chapter 10. Efficiency and Data Representation 339

10.1 The concept of an editor buffer 340

10.2 Defining the buffer abstraction 341 The public interface of the EditorBuffer class; Coding the editor application

10.3 Implementing the editor using arrays 345 Defining the private data representation; Implementing the buffer operations; Assessing the computational complexity of the array implementation

10.4 Implementing the editor using stacks 352 Defining the private data representation for the stack-based buffer; Implementing the buffer operations; Comparing computational complexities

vii

13.2 Binary search trees 459 The underlying motivation for using binary search trees; Finding nodes in a binary search tree; Inserting new nodes in a binary search tree; Tree traversals

13.3 Balanced trees 466 Tree-balancing strategies; Illustrating the AVL idea; Single rotations; Double rotations; Implementing the AVL algorithm

13.4 Defining a general interface for binary search trees 477 Allowing the client to define the node data; Generalizing the types used for keys; Removing nodes; Implementing the binary search tree package; Implementing the map.h interface using binary trees; Using the static keyword

Summary 488 Review questions 489 Programming exercises 492

Chapter 14. Expression Trees 499

14.1 Overview of the interpreter 500

14.2 Understanding the abstract structure of expressions 505 A recursive definition of expressions; Expression trees

14.3 Class hierarchies and inheritance 509

14.4 Defining an inheritance hierarchy for expressions 510 Defining the interface for the expression subclasses

14.5 Implementing the node classes 518 Implementing the methods

14.6 Parsing an expression 522 Parsing and grammars; Parsing without precedence; Adding precedence to the parser

Summary 528 Review questions 528 Programming exercises 530

Chapter 15. Sets 535

15.1 Sets as a mathematical abstraction 536 Membership; Set operations; Identities on sets

15.2 Designing a set interface 539 Defining the element type; Writing the set interface; Character sets; Using sets to avoid duplication

15.3 Implementing the set class 544

15.4 Enhancing the efficiency of integer sets 548 Characteristic vectors; Packed arrays of bits; Bitwise operators; Implementing characteristic vectors using the bitwise operators; Implementing the high-level set operations; Using a hybrid implementation

Summary 555 Review questions 556 Programming exercises 558

viii

Representing connections using an adjacency list; Representing connections using

  • Chapter 16. Graphs
    • 16.1 The structure of a graph
    • 16.2 Implementation strategies for graphs Directed and undirected graphs; Paths and cycles; Connectivity
    • 16.3 Designing a low-level graph abstraction an adjacency matrix; Representing connections using a set of arcs
    • 16.4 Graph traversals Using the low-level graph.h interface
    • 16.5 Defining a Graph class Depth-first search; Breadth-first search
    • 16.6 Finding minimum paths Using classes for graphs, nodes, and arcs; Adopting an intermediate strategy
    • 16.7 An efficient implementation of priority queues
    • Summary
    • Review questions
    • Programming exercises
  • Appendix A. Library Interfaces
    • bst.h
    • cmpfn.h
    • extgraph.h
    • genlib.h
    • graph.h
    • graphics.h
    • grid.h
    • lexicon.h
    • map.h
    • queue.h
    • random.h
    • scanner.h
    • set.h
    • simpio.h
    • sound.h
    • stack.h
    • strutils.h
    • vector.h
  • Index

An Overview of C++ – 2 –

In Lewis Carroll’s Alice’s Adventures in Wonderland, the King asks the White Rabbit to “begin at the beginning and go on till you come to the end: then stop.” Good advice, but only if you’re starting from the beginning. This book is designed for a second course in computer science and therefore assumes that you have already begun your study of programming. At the same time, because first courses vary considerably in what they cover, it is difficult to rely on any specific material. Some of you, for example, will already have experience programming in C or C++. Many of you, however, are coming from a first course taught in some other language.

Because of this wide disparity in background, the best approach is to adopt the King’s advice and begin at the beginning. The first three chapters in this text therefore move quickly through the material I consider to be essential background for the later chapters. Chapters 1 and 2 discuss C++ in general and may be skimmed if you’ve had experience with C++. Chapter 3 discusses standard interfaces and some interfaces particular to this text. By the end of these three chapters, you will be up to speed on the fundamentals of C++ programming.

1.1 What is C++?

In the early days of computing, programs were written in machine language, which consists of the primitive instructions that can be executed directly by the machine. Machine-language programs are difficult to understand, mostly because the structure of machine language reflects the design of the hardware rather than the needs of programmers. In the mid-1950s, a group of programmers under the direction of John Backus at IBM had an idea that profoundly changed the nature of computing. Would it be possible, they wondered, to write programs that resembled the mathematical formulas they were trying to compute and have the computer itself translate those formulas into machine language? In 1955, this team produced the initial version of Fortran (whose name is an abbreviation of formula translation ), which was the first example of a higher- level programming language. Since that time, many new programming languages have been invented, as shown in the evolutionary diagram in Figure 1-1.

Figure 1-1 Evolutionary tree of several major programming languages

An Overview of C++ – 3 –

As Figure 1-1 illustrates, C++ represents the coming together of two branches in the evolution of programming languages. One of its ancestors is a language called C, which was designed at Bell Laboratories by Dennis Ritchie in 1972 and then later revised and standardized by the American National Standards Institute (ANSI) in 1989. But C++ also descends from another line of languages that have dramatically changed the nature of modern programming.

The object-oriented paradigm

Over the last decade or so, computer science and programming have gone through something of a revolution. Like most revolutions—whether political upheavals or the conceptual restructurings that Thomas Kuhn describes in his 1962 book The Structure of Scientific Revolutions —this change has been driven by the emergence of an idea that challenges an existing orthodoxy. Initially, the two ideas compete. For a while, the old order maintains its dominance. Over time, however, the strength and popularity of the new idea grows, until it begins to displace the older idea in what Kuhn calls a paradigm shift. In programming, the old order is represented by the procedural paradigm, in which programs consist of a collection of procedures and functions that operate on data. The challenger is the object-oriented paradigm, in which programs are viewed instead as a collection of data objects that exhibit particular behavior.

The idea of object-oriented programming is not really all that new. The first object- oriented language was SIMULA, a language for coding simulations designed in 1967 by the Scandinavian computer scientists Ole-Johan Dahl, Björn Myhrhaug, and Kristen Nygaard. With a design that was far ahead of its time, SIMULA anticipated many of the concepts that later became commonplace in programming, including the concept of abstract data types and much of the modern object-oriented paradigm. In fact, most of the terminology used to describe object-oriented systems comes from the original 1967 report on SIMULA.

For many years, however, SIMULA mostly just sat on the shelf. Few people paid much attention to it, and the only place you were likely to hear about it would be in a course on programming language design. The first object-oriented language to gain any significant level of recognition within the computing profession was Smalltalk, which was developed at the Xerox Palo Alto Research Center (more commonly known as Xerox PARC) in the late 1970s. The purpose of Smalltalk, which is described in the book Smalltalk-80: The Language and Its Implementation by Adele Goldberg and David Robson, was to make programming accessible to a wider audience. As such, Smalltalk was part of a larger effort at Xerox PARC that gave rise to much of the modern user- interface technology that is now standard on personal-computers.

Despite many attractive features and a highly interactive user environment that simplifies the programming process, Smalltalk never achieved much commercial success. The profession as a whole took an interest in object-oriented programming only when the central ideas were incorporated into variants of C, which had already become an industry standard. Although there were several parallel efforts to design an object-oriented language based on C, the most successful was the language C++, which was designed in the early 1980s by Bjarne Stroustrup at AT&T Bell Laboratories. By making it possible to integrate object-oriented techniques with existing C code, C++ enabled large communities of programmers to adopt the object-oriented paradigm in a gradual, evolutionary way.

Although object-oriented languages are undeniably gaining popularity at the expense of procedural ones, it would be a mistake to regard the object-oriented and procedural paradigms as mutually exclusive. Programming paradigms are not so much competitive

An Overview of C++ – 5 –

1.2 The structure of a C++ program

The best way to get a feeling for the C++ programming language is to look at a sample program such as the one shown in Figure 1-3. This program generates a table comparing the values of N^2 and 2 N^ for various values of N —a comparison that will prove to be important in Chapter 8. The output of the program looks like this:

PowerTable | 2 | N N | N | 2 ----+-----+------ 0 | 0 | 1 1 | 1 | 2 2 | 4 | 4 3 | 9 | 8 4 | 16 | 16 5 | 25 | 32 6 | 36 | 64 7 | 49 | 128 8 | 64 | 256 9 | 81 | 512 10 | 100 | 1024 11 | 121 | 2048 12 | 144 | 4096

As the annotations in Figure 1-3 indicate, the powertab.cpp program is divided into several components, which are discussed in the next few sections.

Comments

Much of the text in Figure 1-3 consists of English-language comments. A comment is text that is ignored by the compiler but which nonetheless conveys information to other programmers. A comment consists of text enclosed between the markers /* and */ and may continue over several lines. Alternatively, a single-line comment is begun by the marker // and continues until the end of the line. The powertab.cpp program includes a comment at the beginning that describes the operation of the program as a whole, one before the definition of the RaiseIntToPower function that describes what it does, and a couple of one-line comments that act very much like section headings in English text.

Library inclusions

The lines beginning with #include such as

#include "genlib.h" #include #include

indicate that the compiler should read in definitions from a header file. The inclusion of a header file indicates that the program uses facilities from a library, which is a collection of prewritten tools that perform a set of useful operations. The different punctuation in these #include lines reflects the fact that the libraries come from different sources. The angle brackets are used to specify a system library, such as the standard input/output stream library ( iostream ) or the stream manipuator library ( iomanip ) that is supplied along with C++. The quotation marks are used for private libraries, including the general library ( genlib ), which was designed for use with the programs in this text. Every program in this book will include at least this library most will require other libraries as well and must contain an #include line for each one.

An Overview of C++ – 6 –

Figure 1-3 Sample program powertab.cpp

*/

  • File: powertab.cpp

  • This program generates a table comparing values
  • of the functions n^2 and 2^n. /*

#include "genlib.h" #include #include

*/

  • Constants

  • LOWER_LIMIT -- Starting value for the table
  • UPPER_LIMIT -- Final value for the table /*

const int LOWER_LIMIT = 0; const int UPPER_LIMIT = 12;

/ Private function prototypes /

int RaiseIntToPower(int n, int k);

/ Main program /

int main() { cout << " | 2 | N" << endl; cout << " N | N | 2" << endl; cout << "----+-----+------" << endl; for (int n = LOWER_LIMIT; n <= UPPER_LIMIT; n++) { cout << setw(3) << n << " |" ; cout << setw(4) << RaiseIntToPower(n, 2) << " |" ; cout << setw(5) << RaiseIntToPower(2, n) << endl; } return 0; }

*/

  • Function: RaiseIntToPower
  • Usage: p = RaiseIntToPower(n, k);

  • This function returns n to the kth power. /*

int RaiseIntToPower(int n, int k) { int result;

*result = 1; for (int i = 0; i < k; i++) { result = n; } return result; }

program comment

library inclusions

main program

constant definitions

function prototype

function definition

local variable declarations

statements forming body of function

section comment

function comment

An Overview of C++ – 8 –

The main program

Every C++ program must contain a function with the name main. This function specifies the starting point for the computation and is called when the program starts up. When main has finished its work and returns, execution of the program ends.

The first three statements of the main function in the powertab.cpp program are sending information to the cout stream to display output on the screen. A few useful notes about streams are included in the section on “Simple input and output” later in this chapter and more features are explored in detail in Chapter 3. At this point, you need to have an informal sense of how to display output to understand any programming example that communicates results to the user. In its simplest form, you use the insertion operator << to put information into the output stream cout. If you insert a string enclosed in double quotes, it will display that string on the console. You must indicate explicitly that you want to move on to the next line by inserting the stream manipulator endl. Thus, the first three lines in main display the header for the table.

The rest of the function main consists of the following code, which is responsible for displaying the table itself:

for (int n = LOWER_LIMIT; n <= UPPER_LIMIT; n++) { cout << setw(3) << n << " |" ; cout << setw(4) << RaiseIntToPower(n, 2) << " |" ; cout << setw(5) << RaiseIntToPower(2, n) << endl; }

This code is an example a for loop, which is used to specify repetition. In this case, the for statement indicates that the body of the loop should be repeated for each of the values of n from LOWER_LIMIT to UPPER_LIMIT. A section on the detailed structure of the for loop appears later in the chapter, but the example shown here represents a common idiomatic pattern that you can use to count between any specified limits.

The body of the loop illustrates an important new feature: the ability to include values as part of the output display. Rather than just displaying fixed strings, we can display numeric values and computed results. We can also use stream manipulators to format the output. Let’s examine the first statement in the body of the loop:

cout << setw(3) << n << " |" ;

This line will display the current value of the variable n followed by a string containing a space and a vertical bar. The setw(3) that is inserted into the stream just before n indicates that the stream should format the next value in a field that is three characters wide. Similarly, the next statement prints the formatted result taken from the expression RaiseIntToPower(n, 2). Obtaining the value of the expression requires making a call on the RaiseIntToPower function, which is discussed in the following section. The value that RaiseIntToPower returns is displayed as part of the output. So is the result of the call to RaiseIntToPower(2, n) , which supplies the value for the third column in the table.

The last statement in main is

return 0;

which indicates that the function result is 0. The return value from the main function is used to communicate the success or failure of the entire program. By convention, a result of 0 indicates success.

An Overview of C++ – 9 –

Function definitions

Because large programs are difficult to understand in their entirety, most programs are broken down into several smaller functions, each of which is easier to understand. In the powertab.cpp program, the function RaiseIntToPower is responsible for raising an integer to a power—an operation that is not built into C++ and must therefore be defined explicitly.

The first line of RaiseIntToPower is the variable declaration

int result;

which introduces a new variable named result capable of holding values of type int , the standard type used to represent integers. The syntax of variable declarations is discussed in more detail in the section on “Variables, values, and types” later in this chapter. For now, all you need to know is that this declaration creates space for an integer variable that you can then use in the body of the function.

The next line in the body of RaiseIntToPower is

result = 1;

This statement is a simple example of an assignment statement, which sets the variable on the left of the equal sign to the value of the expression on the right. In this case, the statement sets the variable result to the constant 1. The next statement in the function is a for loop that executes its body k times. The repeated code consists of the line

*result = n;

which is a C++ shorthand for the English sentence “Multiply result by n .” Because the function initializes the value of result to 1 and then multiplies result by n a total of k times, the variable result ends up with the value n k^.

The last statement in RaiseIntToPower is

return result;

which indicates that the function should return result as the value of the function.

1.3 Variables, values, and types

One of the fundamental characteristics of programs is that they manipulate data. To do so, programs must be able to store data as part of their operation. Moreover, programs today work with many different kinds of data, including numbers and text, along with many more sophisticated data structures, such as those introduced in Part 3 of this book. Learning how to store data of various types is an important part of mastering the basics of any language, including C++.

Variables

Data values in a program are usually stored in variables. In C++, if you want to use a variable to hold some information, you must declare that variable before you use it. Declaring a variable establishes the following properties:

  • Name. Every variable has a name, which is formed according to the rules described in the section entitled “Naming conventions” later in this chapter. You use the name in the program to refer to the variable and the value it contains.

An Overview of C++ – 11 –

Table 1-1 C++ reserved keywords

asm do inline short typeid auto double int signed typename bool dynamic_cast long sizeof union break else mutable static unsigned case enum namespace static_cast using catch explicit new struct virtual char extern operator switch void class false private template volatile const float protected this wchar_t const_cast for public throw while continue friend register true default goto reinterpret_cast try delete if return typedef

with a lowercase letter, such as n1 , total , or string. By contrast, function names, such as RaiseIntToPower , usually begin with an uppercase letter. Moreover, whenever a name consists of several English words run together, the first letter in each word after the first is capitalized to make the name easier to read. By tradition, constant names, such as LOWER_LIMIT are written entirely in uppercase, with underscores between the words.

Local and global variables

Most variables are declared with the body of a function. Such variables are called local variables. The scope of a local variable extends to the end of the block in which it is declared. The lifetime of a local variable is the time during which that function is active. When the function is called, space for each local variable is allocated for the duration of that function call. When the function returns, all its local variables disappear.

If a variable declaration appears outside any function definition, that declaration introduces a global variable. The scope of a global variable is the remainder of the file in which it is declared. Its lifetime continues throughout the entire execution of a program. Global variables are therefore able to store values that persist across function calls. Although they have important applications, global variables can easily be overused. Because global variables can be manipulated by many different functions, it is harder to keep those functions from interfering with each other. Because of these dangers, global variables are used infrequently in this text.

The concept of a data type

One of the reasons C++ requires all variables to be declared is that doing so constrains their contents to values of a particular data type. From a formal perspective, a data type is defined by two properties: a domain, which is the set of values that belong to that type, and a set of operations, which defines the behavior of that type. For example, the domain of the type int includes all integers (... –2, –1, 0, 1, 2.. .) up to the limits established by the hardware of the machine. The set of operations applicable to values of type int includes, for example, the standard arithmetic operations like addition and multiplication. Other types have a different domain and set of operations.

As you will learn in Chapter 2, much of the power of higher-level languages like C++ comes from the fact that you can define new data types from existing ones. To get that process started, C++ includes several fundamental types that are defined as part of the language (or, in the case of string , as part of the standard C++ libraries). These types, which act as the building blocks for the type system as a whole, are called atomic types. These predefined types are grouped into four categories—integer, floating-point, text, and Boolean—which are discussed in the sections that follow.

An Overview of C++ – 12 –

Integer types

Although the concept of an integer seems like a simple one, C++ actually includes several different data types for representing integer values. In most cases, all you need to know is the type int , which corresponds to the standard representation of an integer on the computer system you are using. In certain cases, however, you need to be more careful. Like all data, values of type int are stored internally in storage units that have a limited capacity. Those values therefore have a maximum size, which limits the range of integers you can use. To get around this problem, C++ defines three integer types— short , int , and long —distinguished from each other by the size of their domains.

Unfortunately, the language definition for C++ does not specify an exact range for these three types. As a result, the range for the different integer types depends on the machine and the compiler you’re using. On many personal computers, the maximum value of type int is 32,767, which is rather small by computational standards. If you wanted, for example, to perform a calculation involving the number of seconds in a year, you could not use type int on those machines, because that value (31,536,000) is considerably larger than the largest available value of type int. The only properties you can rely on are the following:

  • The internal size of an integer cannot decrease as you move from short to int to long. A compiler designer for C++ could, for example, decide to make short and int the same size but could not make int smaller than short.
  • The maximum value of type int must be at least 32,767 (2^15 –1).
  • The maximum value of type long must be at least 2,147,483,647 (2^31 –1).

The designers of C++ could have chosen to define the allowable range of type int more precisely. For example, they could have declared—as the designers of Java did— that the maximum value of type int would be 2 31 –1 on every machine. Had they done so, it would be easier to move a program from one system to another and have it behave in the same way. The ability to move a program between different machines is called portability, which is an important consideration in the design of a programming language.

In C++, each of the integer types int , long , and short may be preceded by the keyword unsigned. Adding u n s i g n e d creates a new data type in which only nonnegative values are allowed. Because unsigned variables do not need to represent negative values, declaring a variable to be one of the unsigned types allows it to hold twice as many positive values. For example, if the maximum value of type int is 32,767, the maximum value of type unsigned int will be 65,535. C++ allows the type unsigned int to be abbreviated to unsigned , and most programmers who use this type tend to follow this practice. Sometimes variables intended to store sizes are declared as unsigned, because a size will always be nonnegative.

An integer constant is ordinarily written as a string of digits representing a number in base 10. If the number begins with the digit 0, however, the compiler interprets the value as an octal (base 8) integer. Thus, the constant 040 is taken to be in octal and represents the decimal number 32. If you prefix a numeric constant with the characters 0x , the compiler interprets that number as hexadecimal (base 16). Thus, the constant 0xFF is equivalent to the decimal constant 255. You can explicitly indicate that an integer constant is of type long by adding the letter L at the end of the digit string. Thus, the constant 0L is equal to 0, but the value is explicitly of type long. Similarly, if you use the letter U as a suffix, the constant is taken to be unsigned.