A type alias (§ 2.5.1, p. 67) can make it easier to read, write, and understand point- ers to multidimensional arrays. For example:
using int_array = int[4]; // new style type alias declaration; see § 2.5.1 (p. 68) typedef int int_array[4]; // equivalenttypedefdeclaration; § 2.5.1 (p. 67) // print the value of each element inia, with each inner array on its own line
for (int_array *p = ia; p != ia + 3; ++p) { for (int *q = *p; q != *p + 4; ++q)
cout << *q << ’ ’;
cout << endl;
}
Here we start by definingint_arrayas a name for the type “array of fourints.”
We use that type name to define our loop control variable in the outerforloop.
E
X E R C I S E SS
E C T I O N3.6
Exercise 3.43: Write three different versions of a program to print the elements ofia.
One version should use a rangeforto manage the iteration, the other two should use an ordinaryforloop in one case using subscripts and in the other using pointers. In all three programs write all the types directly. That is, do not use a type alias,auto, or decltypeto simplify the code.
Exercise 3.44: Rewrite the programs from the previous exercises using a type alias for the type of the loop control variables.
Exercise 3.45: Rewrite the programs again, this time usingauto.
ptg11539634
Defined Terms 131
C H A P T E R S U M M A R Y
Among the most important library types arevectorandstring. Astringis a variable-length sequence of characters, and avectoris a container of objects of a single type.
Iterators allow indirect access to objects stored in a container. Iterators are used to access and navigate between the elements instrings andvectors.
Arrays and pointers to array elements provide low-level analogs to thevector andstringlibraries. In general, the library classes should be used in preference to low-level array and pointer alternatives built into the language.
D E F I N E D T E R M S
begin Member of string and vector that returns an iterator to the first ele- ment. Also, free-standing library function that takes an array and returns a pointer to the first element in the array.
buffer overflow Serious programming bug that results when we use an index that is out-of-range for a container, such as a string,vector, or an array.
C-style strings Null-terminated character array. String literals are C-style strings. C- style strings are inherently error-prone.
class template A blueprint from which specific clas types can be created. To use a class template, we must specify addi- tional information. For example, to de- fine avector, we specify the element type:
vector<int>holdsints.
compiler extension Feature that is added to the language by a particular compiler.
Programs that rely on compiler extensions cannot be moved easily to other compilers.
container A type whose objects hold a col- lection of objects of a given type.vectoris a container type.
copy initialization Form of initialization that uses an=. The newly created object is a copy of the given initializer.
difference_type A signed integral type defined by vector andstring that can hold the distance between any two iterators.
direct initialization Form of initialization that does not include an=.
empty Member of string and vector.
Returns bool, which is true if size is zero,falseotherwise.
end Member ofstringandvectorthat returns an off-the-end iterator. Also, free- standing library function that takes an ar- ray and returns a pointer one past the last element in the array.
getline Function defined in the string header that takes an istream and a string. The function reads the stream up to the next newline, storing what it read into thestring, and returns theistream. The newline is read and discarded.
index Value used in the subscript opera- tor to denote the element to retrieve from a string,vector, or array.
instantiation Compiler process that gener- ates a specific template class or function.
iterator A type used to access and navigate among the elements of a container.
iterator arithmetic Operations onvector orstringiterators: Adding or subtracting an integral value and an iterator yields an iterator that many elements ahead of or be- hind the original iterator. Subtracting one iterator from another yields the distance be- tween them. Iterators must refer to ele- ments in, or off-the-end of the same con- tainer.
ptg11539634
132 Defined Terms
null-terminated string String whose last character is followed by the null character (’\0’).
off-the-end iterator The iterator returned byendthat refers to a nonexistent element one past the end of a container.
pointer arithmetic The arithmetic opera- tions that can be applied to pointers. Point- ers to arrays support the same operations as iterator arithmetic.
ptrdiff_t Machine-dependent signed inte- gral type defined in the cstddefheader that is large enough to hold the difference between two pointers into the largest possi- ble array.
push_back Member ofvector. Appends elements to the back of avector.
range for Control statement that iterates through a specified collection of values.
size Member ofstringandvector. Re- turns the number of characters or ele- ments, respectively. Returns a value of the size_typefor the type.
size_t Machine-dependent unsigned inte- gral type defined in the cstddefheader that is large enough to hold the size of the largest possible array.
size_type Name of types defined by the stringandvectorclasses that are capa- ble of containing the size of any string or vector, respectively. Library classes that define size_type define it as an unsignedtype.
string Library type that represents a se- quence of characters.
using declarations Make a name from a namespace accessible directly.
using namespace::name;
makes name accessible without the name- space::prefix.
value initialization Initialization in which built-in types are initialized to zero and
class types are initialized by the class’s de- fault constructor. Objects of a class type can be value initialized only if the class has a de- fault constructor. Used to initialize a con- tainer’s elements when a size, but not an element initializer, is specified. Elements are initialized as a copy of this compiler- generated value.
vector Library type that holds a collection of elements of a specified type.
++operator The iterator types and point- ers define the increment operator to “add one” by moving the iterator to refer to the next element.
[ ]operator Subscript operator. obj[i]
yields the element at position i from the container object obj. Indices count from zero—the first element is element0and the last is the element indexed byobj.size() - 1. Subscript returns an object. Ifpis a pointer andnan integer,p[n]is a synonym for*(p+n).
->operator Arrow operator. Combines the operations of dereference and dot oper- ators:a->bis a synonym for(*a).b.
<<operator Thestringlibrary type de- fines an output operator. Thestringoper- ator prints the characters in astring.
>>operator Thestringlibrary type de- fines an input operator. The stringop- erator reads whitespace-delimited chunks of characters, storing what is read into the right-hand (string) operand.
!operator LogicalNOToperator. Returns the inverse of theboolvalue of its operand.
Result istrueif operand isfalseand vice versa.
&&operator LogicalANDoperator. Result istrue if both operands are true. The right-hand operand is evaluatedonlyif the left-hand operand istrue.
||operator Logical OR operator. Yields trueif either operand istrue. The right- hand operand is evaluatedonlyif the left- hand operand isfalse.
ptg11539634
C H A P T E R 4
E X P R E S S I O N S
C ONTENTS
Section 4.1 Fundamentals . . . 134 Section 4.2 Arithmetic Operators . . . 139 Section 4.3 Logical and Relational Operators . . . 141 Section 4.4 Assignment Operators . . . 144 Section 4.5 Increment and Decrement Operators . . . 147 Section 4.6 The Member Access Operators . . . 150 Section 4.7 The Conditional Operator . . . 151 Section 4.8 The Bitwise Operators . . . 152 Section 4.9 The sizeof Operator . . . 156 Section 4.10 Comma Operator . . . 157 Section 4.11 Type Conversions . . . 159 Section 4.12 Operator Precedence Table . . . 166 Chapter Summary . . . 168 Defined Terms . . . 168
C++ provides a rich set of operators and defines what these operators do when applied to operands of built-in type. It also allows us to de- fine the meaning of most of the operators when applied to operands of class types. This chapter focuses on the operators as defined in the language and applied to operands of built-in type. We will also look at some of the operators defined by the library. Chapter 14 will show how we can define operators for our own types.
133
ptg11539634
134 Expressions
An expression
is composed of one or moreoperandsand yields aresultwhen it is evaluated. The simplest form of anexpressionis a single literal or variable.The result of such an expression is the value of the variable or literal. More com- plicated expressions are formed from anoperatorand one or more operands.
4.1 Fundamentals
There are a few fundamental concepts that affect how expressions are evaluated.
We start by briefly discussing the concepts that apply to most (if not all) expres- sions. Subsequent sections will cover these topics in more detail.
4.1.1 Basic Concepts
There are bothunary operatorsandbinary operators. Unary operators, such as address-of (&) and dereference (*), act on one operand. Binary operators, such as equality (==) and multiplication (*), act on two operands. There is also one ternary operator that takes three operands, and one operator, function call, that takes an unlimited number of operands.
Some symbols, such as *, are used as both a unary (dereference) and a bi- nary (multiplication) operator. The context in which a symbol is used determines whether the symbol represents a unary or binary operator. The uses of such sym- bols are independent; it can be helpful to think of them as two different symbols.