Addison Wesley Stroustrup The C++ Programming Language Special Edition

Loading...

Flash Player 9 (or above) is needed to view presentations.
We have detected that you do not have it on your computer. To install it, go here.

0 comments

Post a comment

    Post a comment
    Embed Video
    Edit your comment Cancel

    2 Favorites

    Addison Wesley Stroustrup The C++ Programming Language Special Edition - Presentation Transcript

    1. The C++ Programming Language Third Edition Bjarne Stroustrup AT&T Labs Murray Hill, New Jersey Addison-Wesley An Imprint of Addison Wesley Longman, Inc. Reading, Massachusetts • Harlow, England • Menlo Park, California Berkeley, California • Don Mills, Ontario • Sydney Bonn • Amsterdam • Tokyo • Mexico City
    2. ii Many of the designations used by manufacturers and sellers to distinguish their products are claimed as trademarks. Where those designations appear in this book, and Addison-Wesley was aware of a trademark claim, the designations have been printed in initial capital letters or all capital letters The author and publisher have taken care in the preparation of this book, but make no expressed or implied warranty of any kind and assume no responsibility for errors or omissions. No liability is assumed for incidental or consequential damages in connection with or arising out of the use of the information contained herein. The publisher offers discounts on this book when ordered in quantity for special sales. For more information please contact: Corporate & Professional Publishing Group Addison-Wesley Publishing Company One Jacob Way Reading, Massachusetts 01867 Library of Congress Cataloging-in-Publication Data Stroustrup, Bjarne The C++ Programming Language / Bjarne Stroustrup. — 3rd. ed. p. cm. Includes index. ISBN 0-201-88954-4 1. C++ (Computer Programming Language) I. Title QA76.73.C153S77 1997 97-20239 005.13’3—dc21 CIP Copyright © 1997 by AT&T All rights reserved. No part of this publication may be reproduced, stored in a retrieval system, or transmitted, in any form or by any means, electronic, mechanical, photocopying, recording, or otherwise, without the prior written permission of the publisher. Printed in the United States of America. This book was typeset in Times and Courier by the author. ISBN 0-201-88954-4 Printed on recycled paper 1 2 3 4 5 6 7 8 9—CRW—0100999897 First printing, June 1997
    3. Contents Contents iii Preface v Preface to Second Edition vii Preface to First Edition ix Introductory Material 1 1 Notes to the Reader ..................................................................... 3 2 A Tour of C++ ............................................................................. 21 3 A Tour of the Standard Library .................................................. 45 Part I: Basic Facilities 67 4 Types and Declarations ............................................................... 69 5 Pointers, Arrays, and Structures .................................................. 87 6 Expressions and Statements ........................................................ 107 7 Functions ..................................................................................... 143 8 Namespaces and Exceptions ....................................................... 165 9 Source Files and Programs .......................................................... 197
    4. iv Contents Part II: Abstraction Mechanisms 221 10 Classes ........................................................................................ 223 11 Operator Overloading ................................................................. 261 12 Derived Classes ........................................................................... 301 13 Templates .................................................................................... 327 14 Exception Handling .................................................................... 355 15 Class Hierarchies ........................................................................ 389 Part III: The Standard Library 427 16 Library Organization and Containers .......................................... 429 17 Standard Containers .................................................................... 461 18 Algorithms and Function Objects ............................................... 507 19 Iterators and Allocators ............................................................... 549 20 Strings ......................................................................................... 579 21 Streams ........................................................................................ 605 22 Numerics ..................................................................................... 657 Part IV: Design Using C++ 689 23 Development and Design ............................................................ 691 24 Design and Programming ........................................................... 723 25 Roles of Classes .......................................................................... 765 Appendices 791 A The C++ Grammar ...................................................................... 793 B Compatibility .............................................................................. 815 C Technicalities .............................................................................. 827 Index 869
    5. Preface Programming is understanding. – Kristen Nygaard I find using C++ more enjoyable than ever. C++’s support for design and programming has improved dramatically over the years, and lots of new helpful techniques have been developed for its use. However, C++ is not just fun. Ordinary practical programmers have achieved significant improvements in productivity, maintainability, flexibility, and quality in projects of just about any kind and scale. By now, C++ has fulfilled most of the hopes I originally had for it, and also suc- ceeded at tasks I hadn’t even dreamt of. This book introduces standard C++† and the key programming and design techniques supported by C++. Standard C++ is a far more powerful and polished language than the version of C++ intro- duced by the first edition of this book. New language features such as namespaces, exceptions, templates, and run-time type identification allow many techniques to be applied more directly than was possible before, and the standard library allows the programmer to start from a much higher level than the bare language. About a third of the information in the second edition of this book came from the first. This third edition is the result of a rewrite of even larger magnitude. It offers something to even the most experienced C++ programmer; at the same time, this book is easier for the novice to approach than its predecessors were. The explosion of C++ use and the massive amount of experience accu- mulated as a result makes this possible. The definition of an extensive standard library makes a difference to the way C++ concepts can be presented. As before, this book presents C++ independently of any particular implementation, and as before, the tutorial chapters present language constructs and concepts in a ‘‘bottom up’’ order so that a construct is used only after it has been defined. However, it is much easier to use a well-designed library than it is to understand the details of its implementation. Therefore, the stan- dard library can be used to provide realistic and interesting examples well before a reader can be assumed to understand its inner workings. The standard library itself is also a fertile source of pro- gramming examples and design techniques. __________________ † ISO/IEC 14882, Standard for the C++ Programming Language.
    6. vi Preface This book presents every major C++ language feature and the standard library. It is organized around language and library facilities. However, features are presented in the context of their use. That is, the focus is on the language as the tool for design and programming rather than on the lan- guage in itself. This book demonstrates key techniques that make C++ effective and teaches the fundamental concepts necessary for mastery. Except where illustrating technicalities, examples are taken from the domain of systems software. A companion, The Annotated C++ Language Stan- dard, presents the complete language definition together with annotations to make it more compre- hensible. The primary aim of this book is to help the reader understand how the facilities offered by C++ support key programming techniques. The aim is to take the reader far beyond the point where he or she gets code running primarily by copying examples and emulating programming styles from other languages. Only a good understanding of the ideas behind the language facilities leads to mastery. Supplemented by implementation documentation, the information provided is sufficient for completing significant real-world projects. The hope is that this book will help the reader gain new insights and become a better programmer and designer. Acknowledgments In addition to the people mentioned in the acknowledgement sections of the first and second edi- tions, I would like to thank Matt Austern, Hans Boehm, Don Caldwell, Lawrence Crowl, Alan Feuer, Andrew Forrest, David Gay, Tim Griffin, Peter Juhl, Brian Kernighan, Andrew Koenig, Mike Mowbray, Rob Murray, Lee Nackman, Joseph Newcomer, Alex Stepanov, David Vandevo- orde, Peter Weinberger, and Chris Van Wyk for commenting on draft chapters of this third edition. Without their help and suggestions, this book would have been harder to understand, contained more errors, been slightly less complete, and probably been a little bit shorter. I would also like to thank the volunteers on the C++ standards committees who did an immense amount of constructive work to make C++ what it is today. It is slightly unfair to single out indi- viduals, but it would be even more unfair not to mention anyone, so I’d like to especially mention .. Mike Ball, Dag Bruck, Sean Corfield, Ted Goldstein, Kim Knuttila, Andrew Koenig, Josée Lajoie, Dmitry Lenkov, Nathan Myers, Martin O’Riordan, Tom Plum, Jonathan Shopiro, John Spicer, Jerry Schwarz, Alex Stepanov, and Mike Vilot, as people who each directly cooperated with me over some part of C++ and its standard library. Murray Hill, New Jersey Bjarne Stroustrup
    7. Preface to the Second Edition The road goes ever on and on. – Bilbo Baggins As promised in the first edition of this book, C++ has been evolving to meet the needs of its users. This evolution has been guided by the experience of users of widely varying backgrounds working in a great range of application areas. The C++ user-community has grown a hundredfold during the six years since the first edition of this book; many lessons have been learned, and many techniques have been discovered and/or validated by experience. Some of these experiences are reflected here. The primary aim of the language extensions made in the last six years has been to enhance C++ as a language for data abstraction and object-oriented programming in general and to enhance it as a tool for writing high-quality libraries of user-defined types in particular. A ‘‘high-quality library,’’ is a library that provides a concept to a user in the form of one or more classes that are convenient, safe, and efficient to use. In this context, safe means that a class provides a specific type-safe interface between the users of the library and its providers; efficient means that use of the class does not impose significant overheads in run-time or space on the user compared with hand- written C code. This book presents the complete C++ language. Chapters 1 through 10 give a tutorial introduc- tion; Chapters 11 through 13 provide a discussion of design and software development issues; and, finally, the complete C++ reference manual is included. Naturally, the features added and resolu- tions made since the original edition are integral parts of the presentation. They include refined overloading resolution, memory management facilities, and access control mechanisms, type-safe linkage, c on st and s ta ti c member functions, abstract classes, multiple inheritance, templates, and co ns t st at ic exception handling. C++ is a general-purpose programming language; its core application domain is systems pro- gramming in the broadest sense. In addition, C++ is successfully used in many application areas that are not covered by this label. Implementations of C++ exist from some of the most modest microcomputers to the largest supercomputers and for almost all operating systems. Consequently, this book describes the C++ language itself without trying to explain a particular implementation, programming environment, or library. This book presents many examples of classes that, though useful, should be classified as ‘‘toys.’’ This style of exposition allows general principles and useful techniques to stand out more
    8. viii Preface to the Second Edition clearly than they would in a fully elaborated program, where they would be buried in details. Most of the useful classes presented here, such as linked lists, arrays, character strings, matrices, graphics classes, associative arrays, etc., are available in ‘‘bulletproof’’ and/or ‘‘goldplated’’ versions from a wide variety of commercial and non-commercial sources. Many of these ‘‘industrial strength’’ classes and libraries are actually direct and indirect descendants of the toy versions found here. This edition provides a greater emphasis on tutorial aspects than did the first edition of this book. However, the presentation is still aimed squarely at experienced programmers and endeavors not to insult their intelligence or experience. The discussion of design issues has been greatly expanded to reflect the demand for information beyond the description of language features and their immediate use. Technical detail and precision have also been increased. The reference man- ual, in particular, represents many years of work in this direction. The intent has been to provide a book with a depth sufficient to make more than one reading rewarding to most programmers. In other words, this book presents the C++ language, its fundamental principles, and the key tech- niques needed to apply it. Enjoy! Acknowledgments In addition to the people mentioned in the acknowledgements section in the preface to the first edi- tion, I would like to thank Al Aho, Steve Buroff, Jim Coplien, Ted Goldstein, Tony Hansen, Lor- raine Juhl, Peter Juhl, Brian Kernighan, Andrew Koenig, Bill Leggett, Warren Montgomery, Mike Mowbray, Rob Murray, Jonathan Shopiro, Mike Vilot, and Peter Weinberger for commenting on draft chapters of this second edition. Many people influenced the development of C++ from 1985 to 1991. I can mention only a few: Andrew Koenig, Brian Kernighan, Doug McIlroy, and Jonathan Shopiro. Also thanks to the many participants of the ‘‘external reviews’’ of the reference manual drafts and to the people who suffered through the first year of X3J16. Murray Hill, New Jersey Bjarne Stroustrup
    9. Preface to the First Edition Language shapes the way we think, and determines what we can think about. – B.L.Whorf C++ is a general purpose programming language designed to make programming more enjoyable for the serious programmer. Except for minor details, C++ is a superset of the C programming lan- guage. In addition to the facilities provided by C, C++ provides flexible and efficient facilities for defining new types. A programmer can partition an application into manageable pieces by defining new types that closely match the concepts of the application. This technique for program construc- tion is often called data abstraction. Objects of some user-defined types contain type information. Such objects can be used conveniently and safely in contexts in which their type cannot be deter- mined at compile time. Programs using objects of such types are often called object based. When used well, these techniques result in shorter, easier to understand, and easier to maintain programs. The key concept in C++ is class. A class is a user-defined type. Classes provide data hiding, guaranteed initialization of data, implicit type conversion for user-defined types, dynamic typing, user-controlled memory management, and mechanisms for overloading operators. C++ provides much better facilities for type checking and for expressing modularity than C does. It also contains improvements that are not directly related to classes, including symbolic constants, inline substitu- tion of functions, default function arguments, overloaded function names, free store management operators, and a reference type. C++ retains C’s ability to deal efficiently with the fundamental objects of the hardware (bits, bytes, words, addresses, etc.). This allows the user-defined types to be implemented with a pleasing degree of efficiency. C++ and its standard libraries are designed for portability. The current implementation will run on most systems that support C. C libraries can be used from a C++ program, and most tools that support programming in C can be used with C++. This book is primarily intended to help serious programmers learn the language and use it for nontrivial projects. It provides a complete description of C++, many complete examples, and many more program fragments.
    10. x Preface to the First Edition Acknowledgments C++ could never have matured without the constant use, suggestions, and constructive criticism of many friends and colleagues. In particular, Tom Cargill, Jim Coplien, Stu Feldman, Sandy Fraser, Steve Johnson, Brian Kernighan, Bart Locanthi, Doug McIlroy, Dennis Ritchie, Larry Rosler, Jerry Schwarz, and Jon Shopiro provided important ideas for development of the language. Dave Pre- sotto wrote the current implementation of the stream I/O library. In addition, hundreds of people contributed to the development of C++ and its compiler by sending me suggestions for improvements, descriptions of problems they had encountered, and compiler errors. I can mention only a few: Gary Bishop, Andrew Hume, Tom Karzes, Victor Milenkovic, Rob Murray, Leonie Rose, Brian Schmult, and Gary Walker. Many people have also helped with the production of this book, in particular, Jon Bentley, Laura Eaves, Brian Kernighan, Ted Kowalski, Steve Mahaney, Jon Shopiro, and the participants in the C++ course held at Bell Labs, Columbus, Ohio, June 26-27, 1985. Murray Hill, New Jersey Bjarne Stroustrup
    11. Introduction This introduction gives an overview of the major concepts and features of the C++ pro- gramming language and its standard library. It also provides an overview of this book and explains the approach taken to the description of the language facilities and their use. In addition, the introductory chapters present some background information about C++, the design of C++, and the use of C++. Chapters 1 Notes to the Reader 2 A Tour of C++ 3 A Tour of the Standard Library
    12. 2 Introduction Introduction ‘‘... and you, Marcus, you have given me many things; now I shall give you this good advice. Be many people. Give up the game of being always Marcus Cocoza. You have worried too much about Marcus Cocoza, so that you have been really his slave and prisoner. You have not done anything without first considering how it would affect Marcus Cocoza’s happiness and prestige. You were always much afraid that Marcus might do a stupid thing, or be bored. What would it really have mattered? All over the world people are doing stupid things ... I should like you to be easy, your lit- tle heart to be light again. You must from now, be more than one, many people, as many as you can think of ...’’ – Karen Blixen (‘‘The Dreamers’’ from ‘‘Seven Gothic Tales’’ written under the pseudonym Isak Dinesen, Random House, Inc. Copyright, Isac Dinesen, 1934 renewed 1961)
    13. ________________________________________ ________________________________________________________________________________________________________________________________________________________________ 1 ________________________________________ ________________________________________________________________________________________________________________________________________________________________ Notes to the Reader \"The time has come,\" the Walrus said, \"to talk of many things.\" – L.Carroll Structure of this book — how to learn C++ — the design of C++ — efficiency and struc- ture — philosophical note — historical note — what C++ is used for — C and C++ — suggestions for C programmers — suggestions for C++ programmers — thoughts about programming in C++ — advice — references. 1.1 The Structure of This Book This book consists of six parts: Introduction: Chapters 1 through 3 give an overview of the C++ language, the key programming styles it supports, and the C++ standard library. Part I: Chapters 4 through 9 provide a tutorial introduction to C++’s built-in types and the basic facilities for constructing programs out of them. Part II: Chapters 10 through 15 are a tutorial introduction to object-oriented and generic pro- gramming using C++. Part III: Chapters 16 through 22 present the C++ standard library. Part IV: Chapters 23 through 25 discuss design and software development issues. Appendices: Appendices A through E provide language-technical details. Chapter 1 provides an overview of this book, some hints about how to use it, and some background information about C++ and its use. You are encouraged to skim through it, read what appears inter- esting, and return to it after reading other parts of the book. Chapters 2 and 3 provide an overview of the major concepts and features of the C++ program- ming language and its standard library. Their purpose is to motivate you to spend time on funda- mental concepts and basic language features by showing what can be expressed using the complete
    14. 4 Notes to the Reader Chapter 1 C++ language. If nothing else, these chapters should convince you that C++ isn’t (just) C and that C++ has come a long way since the first and second editions of this book. Chapter 2 gives a high- level acquaintance with C++. The discussion focuses on the language features supporting data abstraction, object-oriented programming, and generic programming. Chapter 3 introduces the basic principles and major facilities of the standard library. This allows me to use standard library facilities in the following chapters. It also allows you to use library facilities in exercises rather than relying directly on lower-level, built-in features. The introductory chapters provide an example of a general technique that is applied throughout this book: to enable a more direct and realistic discussion of some technique or feature, I occasion- ally present a concept briefly at first and then discuss it in depth later. This approach allows me to present concrete examples before a more general treatment of a topic. Thus, the organization of this book reflects the observation that we usually learn best by progressing from the concrete to the abstract – even where the abstract seems simple and obvious in retrospect. Part I describes the subset of C++ that supports the styles of programming traditionally done in C or Pascal. It covers fundamental types, expressions, and control structures for C++ programs. Modularity – as supported by namespaces, source files, and exception handling – is also discussed. I assume that you are familiar with the fundamental programming concepts used in Part I. For example, I explain C++’s facilities for expressing recursion and iteration, but I do not spend much time explaining how these concepts are useful. Part II describes C++’s facilities for defining and using new types. Concrete and abstract classes (interfaces) are presented here (Chapter 10, Chapter 12), together with operator overloading (Chapter 11), polymorphism, and the use of class hierarchies (Chapter 12, Chapter 15). Chapter 13 presents templates, that is, C++’s facilities for defining families of types and functions. It demon- strates the basic techniques used to provide containers, such as lists, and to support generic pro- gramming. Chapter 14 presents exception handling, discusses techniques for error handling, and presents strategies for fault tolerance. I assume that you either aren’t well acquainted with object- oriented programming and generic programming or could benefit from an explanation of how the main abstraction techniques are supported by C++. Thus, I don’t just present the language features supporting the abstraction techniques; I also explain the techniques themselves. Part IV goes fur- ther in this direction. Part III presents the C++ standard library. The aim is to provide an understanding of how to use the library, to demonstrate general design and programming techniques, and to show how to extend the library. The library provides containers (such as l is t, v ec to r, and m ap Chapter 16, Chapter 17), li st ve ct or ma p; standard algorithms (such as s or t, f in d, and m er ge Chapter 18, Chapter 19), strings (Chapter 20), so rt fi nd me rg e; Input/Output (Chapter 21), and support for numerical computation (Chapter 22). Part IV discusses issues that arise when C++ is used in the design and implementation of large software systems. Chapter 23 concentrates on design and management issues. Chapter 24 discusses the relation between the C++ programming language and design issues. Chapter 25 presents some ways of using classes in design. Appendix A is C++’s grammar, with a few annotations. Appendix B discusses the relation between C and C++ and between Standard C++ (also called ISO C++ and ANSI C++) and the ver- sions of C++ that preceded it. Appendix C presents some language-technical examples. Appendix D explains the standard library’s facilities supporting internationalization. Appendix E discusses the exception-safety guarantees and requirements of the standard library.
    15. Section 1.1.1 Examples and References 5 1.1.1 Examples and References This book emphasizes program organization rather than the writing of algorithms. Consequently, I avoid clever or harder-to-understand algorithms. A trivial algorithm is typically better suited to illustrate an aspect of the language definition or a point about program structure. For example, I use a Shell sort where, in real code, a quicksort would be better. Often, reimplementation with a more suitable algorithm is an exercise. In real code, a call of a library function is typically more appropriate than the code used here for illustration of language features. Textbook examples necessarily give a warped view of software development. By clarifying and simplifying the examples, the complexities that arise from scale disappear. I see no substitute for writing realistically-sized programs for getting an impression of what programming and a program- ming language are really like. This book concentrates on the language features, the basic tech- niques from which every program is composed, and the rules for composition. The selection of examples reflects my background in compilers, foundation libraries, and simu- lations. Examples are simplified versions of what is found in real code. The simplification is nec- essary to keep programming language and design points from getting lost in details. There are no ‘‘cute’’ examples without counterparts in real code. Wherever possible, I relegated to Appendix C language-technical examples of the sort that use variables named x and y types called A and B and y, B, functions called f and g f() g(). In code examples, a proportional-width font is used for identifiers. For example: #i nc lu de io st re am in cl ud e<i os tr ea m> i nt m ai n() in t ma in { s td :c ou t << \"H el lo n ew w or ld \\n st d: co ut He ll o, ne w wo rl d!\\ n\"; } At first glance, this presentation style will seem ‘‘unnatural’’ to programmers accustomed to seeing code in constant-width fonts. However, proportional-width fonts are generally regarded as better than constant-width fonts for presentation of text. Using a proportional-width font also allows me to present code with fewer illogical line breaks. Furthermore, my experiments show that most peo- ple find the new style more readable after a short while. Where possible, the C++ language and library features are presented in the context of their use rather than in the dry manner of a manual. The language features presented and the detail in which they are described reflect my view of what is needed for effective use of C++. A companion, The Annotated C++ Language Standard, authored by Andrew Koenig and myself, is the complete defi- nition of the language together with comments aimed at making it more accessible. Logically, there ought to be another companion, The Annotated C++ Standard Library. However, since both time and my capacity for writing are limited, I cannot promise to produce that. References to parts of this book are of the form §2.3.4 (Chapter 2, section 3, subsection 4), §B.5.6 (Appendix B, subsection 5.6), and §6.6[10] (Chapter 6, exercise 10). Italics are used spar- ingly for emphasis (e.g., ‘‘a string literal is not acceptable’’), for first occurrences of important con- cepts (e.g., polymorphism), for nonterminals of the C++ grammar (e.g., for-statement), and for com- ments in code examples. Semi-bold italics are used to refer to identifiers, keywords, and numeric values from code examples (e.g., c ou nt er c la ss and 1 71 2). co un te r, cl as s, 17 12
    16. 6 Notes to the Reader Chapter 1 1.1.2 Exercises Exercises are found at the ends of chapters. The exercises are mainly of the write-a-program vari- ety. Always write enough code for a solution to be compiled and run with at least a few test cases. The exercises vary considerably in difficulty, so they are marked with an estimate of their diffi- culty. The scale is exponential so that if a (∗1) exercise takes you ten minutes, a (∗2) might take an hour, and a (∗3) might take a day. The time needed to write and test a program depends more on your experience than on the exercise itself. A (∗1) exercise might take a day if you first have to get acquainted with a new computer system in order to run it. On the other hand, a (∗5) exercise might be done in an hour by someone who happens to have the right collection of programs handy. Any book on programming in C can be used as a source of extra exercises for Part I. Any book on data structures and algorithms can be used as a source of exercises for Parts II and III. 1.1.3 Implementation Note The language used in this book is ‘‘pure C++’’ as defined in the C++ standard [C++,1998]. There- fore, the examples ought to run on every C++ implementation. The major program fragments in this book were tried using several C++ implementations. Examples using features only recently adopted into C++ didn’t compile on every implementation. However, I see no point in mentioning which implementations failed to compile which examples. Such information would soon be out of date because implementers are working hard to ensure that their implementations correctly accept every C++ feature. See Appendix B for suggestions on how to cope with older C++ compilers and with code written for C compilers. 1.2 Learning C++ The most important thing to do when learning C++ is to focus on concepts and not get lost in language-technical details. The purpose of learning a programming language is to become a better programmer; that is, to become more effective at designing and implementing new systems and at maintaining old ones. For this, an appreciation of programming and design techniques is far more important than an understanding of details; that understanding comes with time and practice. C++ supports a variety of programming styles. All are based on strong static type checking, and most aim at achieving a high level of abstraction and a direct representation of the programmer’s ideas. Each style can achieve its aims effectively while maintaining run-time and space efficiency. A programmer coming from a different language (say C, Fortran, Smalltalk, Lisp, ML, Ada, Eiffel, Pascal, or Modula-2) should realize that to gain the benefits of C++, they must spend time learning and internalizing programming styles and techniques suitable to C++. The same applies to pro- grammers used to an earlier and less expressive version of C++. Thoughtlessly applying techniques effective in one language to another typically leads to awk- ward, poorly performing, and hard-to-maintain code. Such code is also most frustrating to write because every line of code and every compiler error message reminds the programmer that the lan- guage used differs from ‘‘the old language.’’ You can write in the style of Fortran, C, Smalltalk, etc., in any language, but doing so is neither pleasant nor economical in a language with a different philosophy. Every language can be a fertile source of ideas of how to write C++ programs.
    17. Learning C++ Section 1.2 7 However, ideas must be transformed into something that fits with the general structure and type system of C++ in order to be effective in the different context. Over the basic type system of a lan- guage, only Pyrrhic victories are possible. C++ supports a gradual approach to learning. How you approach learning a new programming language depends on what you already know and what you aim to learn. There is no one approach that suits everyone. My assumption is that you are learning C++ to become a better programmer and designer. That is, I assume that your purpose in learning C++ is not simply to learn a new syn- tax for doing things the way you used to, but to learn new and better ways of building systems. This has to be done gradually because acquiring any significant new skill takes time and requires practice. Consider how long it would take to learn a new natural language well or to learn to play a new musical instrument well. Becoming a better system designer is easier and faster, but not as much easier and faster as most people would like it to be. It follows that you will be using C++ – often for building real systems – before understanding every language feature and technique. By supporting several programming paradigms (Chapter 2), C++ supports productive programming at several levels of expertise. Each new style of program- ming adds another tool to your toolbox, but each is effective on its own and each adds to your effectiveness as a programmer. C++ is organized so that you can learn its concepts in a roughly lin- ear order and gain practical benefits along the way. This is important because it allows you to gain benefits roughly in proportion to the effort expended. In the continuing debate on whether one needs to learn C before C++, I am firmly convinced that it is best to go directly to C++. C++ is safer, more expressive, and reduces the need to focus on low-level techniques. It is easier for you to learn the trickier parts of C that are needed to compen- sate for its lack of higher-level facilities after you have been exposed to the common subset of C and C++ and to some of the higher-level techniques supported directly in C++. Appendix B is a guide for programmers going from C++ to C, say, to deal with legacy code. Several independently developed and distributed implementations of C++ exist. A wealth of tools, libraries, and software development environments are also available. A mass of textbooks, manuals, journals, newsletters, electronic bulletin boards, mailing lists, conferences, and courses are available to inform you about the latest developments in C++, its use, tools, libraries, implemen- tations, etc. If you plan to use C++ seriously, I strongly suggest that you gain access to such sources. Each has its own emphasis and bias, so use at least two. For example, see [Barton,1994], [Booch,1994], [Henricson,1997], [Koenig,1997], [Martin,1995]. 1.3 The Design of C++ Simplicity was an important design criterion: where there was a choice between simplifying the language definition and simplifying the compiler, the former was chosen. However, great impor- tance was attached to retaining a high degree of compatibility with C [Koenig,1989] [Strous- trup,1994] (Appendix B); this precluded cleaning up the C syntax. C++ has no built-in high-level data types and no high-level primitive operations. For example, the C++ language does not provide a matrix type with an inversion operator or a string type with a concatenation operator. If a user wants such a type, it can be defined in the language itself. In fact, defining a new general-purpose or application-specific type is the most fundamental programming
    18. 8 Notes to the Reader Chapter 1 activity in C++. A well-designed user-defined type differs from a built-in type only in the way it is defined, not in the way it is used. The C++ standard library described in Part III provides many examples of such types and their uses. From a user’s point of view, there is little difference between a built-in type and a type provided by the standard library. Features that would incur run-time or memory overheads even when not used were avoided in the design of C++. For example, constructs that would make it necessary to store ‘‘housekeeping information’’ in every object were rejected, so if a user declares a structure consisting of two 16-bit quantities, that structure will fit into a 32-bit register. C++ was designed to be used in a traditional compilation and run-time environment, that is, the C programming environment on the UNIX system. Fortunately, C++ was never restricted to UNIX; it simply used UNIX and C as a model for the relationships between language, libraries, compilers, linkers, execution environments, etc. That minimal model helped C++ to be successful on essen- tially every computing platform. There are, however, good reasons for using C++ in environments that provide significantly more support. Facilities such as dynamic loading, incremental compila- tion, and a database of type definitions can be put to good use without affecting the language. C++ type-checking and data-hiding features rely on compile-time analysis of programs to pre- vent accidental corruption of data. They do not provide secrecy or protection against someone who is deliberately breaking the rules. They can, however, be used freely without incurring run-time or space overheads. The idea is that to be useful, a language feature must not only be elegant; it must also be affordable in the context of a real program. For a systematic and detailed description of the design of C++, see [Stroustrup,1994]. 1.3.1 Efficiency and Structure C++ was developed from the C programming language and, with few exceptions, retains C as a subset. The base language, the C subset of C++, is designed to ensure a very close correspondence between its types, operators, and statements and the objects that computers deal with directly: num- bers, characters, and addresses. Except for the n ew d el et e, t yp ei d, d yn am ic _c as t, and t hr ow oper- ne w, de le te ty pe id dy na mi c_ ca st th ro w ators and the try-block, individual C++ expressions and statements need no run-time support. C++ can use the same function call and return sequences as C – or more efficient ones. When even such relatively efficient mechanisms are too expensive, a C++ function can be substituted inline, so that we can enjoy the notational convenience of functions without run-time overhead. One of the original aims for C was to replace assembly coding for the most demanding systems programming tasks. When C++ was designed, care was taken not to compromise the gains in this area. The difference between C and C++ is primarily in the degree of emphasis on types and struc- ture. C is expressive and permissive. C++ is even more expressive. However, to gain that increase in expressiveness, you must pay more attention to the types of objects. Knowing the types of objects, the compiler can deal correctly with expressions when you would otherwise have had to specify operations in painful detail. Knowing the types of objects also enables the compiler to detect errors that would otherwise persist until testing – or even later. Note that using the type sys- tem to check function arguments, to protect data from accidental corruption, to provide new types, to provide new operators, etc., does not increase run-time or space overheads in C++. The emphasis on structure in C++ reflects the increase in the scale of programs written since C was designed. You can make a small program (say, 1,000 lines) work through brute force even
    19. Section 1.3.1 Efficiency and Structure 9 when breaking every rule of good style. For a larger program, this is simply not so. If the structure of a 100,000-line program is bad, you will find that new errors are introduced as fast as old ones are removed. C++ was designed to enable larger programs to be structured in a rational way so that it would be reasonable for a single person to cope with far larger amounts of code. In addition, the aim was to have an average line of C++ code express much more than the average line of C or Pas- cal code. C++ has by now been shown to over-fulfill these goals. Not every piece of code can be well-structured, hardware-independent, easy-to-read, etc. C++ possesses features that are intended for manipulating hardware facilities in a direct and efficient way without regard for safety or ease of comprehension. It also possesses facilities for hiding such code behind elegant and safe interfaces. Naturally, the use of C++ for larger programs leads to the use of C++ by groups of program- mers. C++’s emphasis on modularity, strongly typed interfaces, and flexibility pays off here. C++ has as good a balance of facilities for writing large programs as any language has. However, as programs get larger, the problems associated with their development and maintenance shift from being language problems to more global problems of tools and management. Part IV explores some of these issues. This book emphasizes techniques for providing general-purpose facilities, generally useful types, libraries, etc. These techniques will serve programmers of small programs as well as pro- grammers of large ones. Furthermore, because all nontrivial programs consist of many semi- independent parts, the techniques for writing such parts serve programmers of all applications. You might suspect that specifying a program by using a more detailed type structure would lead to a larger program source text. With C++, this is not so. A C++ program declaring function argu- ment types, using classes, etc., is typically a bit shorter than the equivalent C program not using these facilities. Where libraries are used, a C++ program will appear much shorter than its C equiv- alent, assuming, of course, that a functioning C equivalent could have been built. 1.3.2 Philosophical Note A programming language serves two related purposes: it provides a vehicle for the programmer to specify actions to be executed, and it provides a set of concepts for the programmer to use when thinking about what can be done. The first purpose ideally requires a language that is ‘‘close to the machine’’ so that all important aspects of a machine are handled simply and efficiently in a way that is reasonably obvious to the programmer. The C language was primarily designed with this in mind. The second purpose ideally requires a language that is ‘‘close to the problem to be solved’’ so that the concepts of a solution can be expressed directly and concisely. The facilities added to C to create C++ were primarily designed with this in mind. The connection between the language in which we think/program and the problems and solu- tions we can imagine is very close. For this reason, restricting language features with the intent of eliminating programmer errors is at best dangerous. As with natural languages, there are great ben- efits from being at least bilingual. A language provides a programmer with a set of conceptual tools; if these are inadequate for a task, they will simply be ignored. Good design and the absence of errors cannot be guaranteed merely by the presence or the absence of specific language features. The type system should be especially helpful for nontrivial tasks. The C++ class concept has, in fact, proven itself to be a powerful conceptual tool.
    20. 10 Notes to the Reader Chapter 1 1.4 Historical Note I invented C++, wrote its early definitions, and produced its first implementation. I chose and for- mulated the design criteria for C++, designed all its major facilities, and was responsible for the processing of extension proposals in the C++ standards committee. Clearly, C++ owes much to C [Kernighan,1978]. Except for closing a few serious loopholes in the type system (see Appendix B), C is retained as a subset. I also retained C’s emphasis on facili- ties that are low-level enough to cope with the most demanding systems programming tasks. C in turn owes much to its predecessor BCPL [Richards,1980]; in fact, BCPL’s // comment convention was (re)introduced in C++. The other main source of inspiration for C++ was Simula67 [Dahl,1970] [Dahl,1972]; the class concept (with derived classes and virtual functions) was bor- rowed from it. C++’s facility for overloading operators and the freedom to place a declaration wherever a statement can occur resembles Algol68 [Woodward,1974]. Since the original edition of this book, the language has been extensively reviewed and refined. The major areas for revision were overload resolution, linking, and memory management facilities. In addition, several minor changes were made to increase C compatibility. Several generalizations and a few major extensions were added: these included multiple inheritance, s ta ti c member func- st at ic tions, c on st member functions, p ro te ct ed members, templates, exception handling, run-time type co ns t pr ot ec te d identification, and namespaces. The overall theme of these extensions and revisions was to make C++ a better language for writing and using libraries. The evolution of C++ is described in [Strous- trup,1994]. The template facility was primarily designed to support statically typed containers (such as lists, vectors, and maps) and to support elegant and efficient use of such containers (generic program- ming). A key aim was to reduce the use of macros and casts (explicit type conversion). Templates were partly inspired by Ada’s generics (both their strengths and their weaknesses) and partly by Clu’s parameterized modules. Similarly, the C++ exception-handling mechanism was inspired .. partly by Ada [Ichbiah,1979], Clu [Liskov,1979], and ML [Wikstrom,1987]. Other developments in the 1985 to 1995 time span – such as multiple inheritance, pure virtual functions, and name- spaces – were primarily generalizations driven by experience with the use of C++ rather than ideas imported from other languages. Earlier versions of the language, collectively known as ‘‘C with Classes’’ [Stroustrup,1994], have been in use since 1980. The language was originally invented because I wanted to write some event-driven simulations for which Simula67 would have been ideal, except for efficiency consid- erations. ‘‘C with Classes’’ was used for major projects in which the facilities for writing programs that use minimal time and space were severely tested. It lacked operator overloading, references, virtual functions, templates, exceptions, and many details. The first use of C++ outside a research organization started in July 1983. The name C++ (pronounced ‘‘see plus plus’’) was coined by Rick Mascitti in the summer of 1983. The name signifies the evolutionary nature of the changes from C; ‘‘++’’ is the C increment operator. The slightly shorter name ‘‘C+’’ is a syntax error; it has also been used as the name of an unrelated language. Connoisseurs of C semantics find C++ inferior to ++C. The language is not called D, because it is an extension of C, and it does not attempt to remedy problems by removing features. For yet another interpretation of the name C++, see the appendix of [Orwell,1949]. C++ was designed primarily so that my friends and I would not have to program in assembler,
    21. Section 1.4 Historical Note 11 C, or various modern high-level languages. Its main purpose was to make writing good programs easier and more pleasant for the individual programmer. In the early years, there was no C++ paper design; design, documentation, and implementation went on simultaneously. There was no ‘‘C++ project’’ either, or a ‘‘C++ design committee.’’ Throughout, C++ evolved to cope with problems encountered by users and as a result of discussions between my friends, my colleagues, and me. Later, the explosive growth of C++ use caused some changes. Sometime during 1987, it became clear that formal standardization of C++ was inevitable and that we needed to start prepar- ing the ground for a standardization effort [Stroustrup,1994]. The result was a conscious effort to maintain contact between implementers of C++ compilers and major users through paper and elec- tronic mail and through face-to-face meetings at C++ conferences and elsewhere. AT&T Bell Laboratories made a major contribution to this by allowing me to share drafts of revised versions of the C++ reference manual with implementers and users. Because many of these people work for companies that could be seen as competing with AT&T, the significance of this contribution should not be underestimated. A less enlightened company could have caused major problems of language fragmentation simply by doing nothing. As it happened, about a hundred individuals from dozens of organizations read and commented on what became the generally accepted reference manual and the base document for the ANSI C++ standardization effort. Their names can be found in The Annotated C++ Reference Manual [Ellis,1989]. Finally, the X3J16 committee of ANSI was convened in December 1989 at the initiative of Hewlett-Packard. In June 1991, this ANSI (American national) standardization of C++ became part of an ISO (international) standardization effort for C++. From 1990, these joint C++ standards committees have been the main forum for the evolution of C++ and the refinement of its definition. I served on these commit- tees throughout. In particular, as the chairman of the working group for extensions, I was directly responsible for the handling of proposals for major changes to C++ and the addition of new lan- guage features. An initial draft standard for public review was produced in April 1995. The ISO C++ standard (ISO/IEC 14882) was ratified in 1998. C++ evolved hand-in-hand with some of the key classes presented in this book. For example, I designed complex, vector, and stack classes together with the operator overloading mechanisms. String and list classes were developed by Jonathan Shopiro and me as part of the same effort. Jonathan’s string and list classes were the first to see extensive use as part of a library. The string class from the standard C++ library has its roots in these early efforts. The task library described in [Stroustrup,1987] and in §12.7[11] was part of the first ‘‘C with Classes’’ program ever written. I wrote it and its associated classes to support Simula-style simulations. The task library has been revised and reimplemented, notably by Jonathan Shopiro, and is still in extensive use. The stream library as described in the first edition of this book was designed and implemented by me. Jerry Schwarz transformed it into the iostreams library (Chapter 21) using Andrew Koenig’s manipulator technique (§21.4.6) and other ideas. The iostreams library was further refined during standardiza- tion, when the bulk of the work was done by Jerry Schwarz, Nathan Myers, and Norihiro Kumagai. The development of the template facility was influenced by the v ec to r, m ap l is t, and s or t tem- ve ct or ma p, li st so rt plates devised by Andrew Koenig, Alex Stepanov, me, and others. In turn, Alex Stepanov’s work on generic programming using templates led to the containers and algorithms parts of the standard C++ library (§16.3, Chapter 17, Chapter 18, §19.2). The v al ar ra y library for numerical computa- va la rr ay tion (Chapter 22) is primarily the work of Kent Budge.
    22. 12 Notes to the Reader Chapter 1 1.5 Use of C++ C++ is used by hundreds of thousands of programmers in essentially every application domain. This use is supported by about a dozen independent implementations, hundreds of libraries, hun- dreds of textbooks, several technical journals, many conferences, and innumerable consultants. Training and education at a variety of levels are widely available. Early applications tended to have a strong systems programming flavor. For example, several major operating systems have been written in C++ [Campbell,1987] [Rozier,1988] [Hamilton,1993] [Berg,1995] [Parrington,1995] and many more have key parts done in C++. I considered uncom- promising low-level efficiency essential for C++. This allows us to use C++ to write device drivers and other software that rely on direct manipulation of hardware under real-time constraints. In such code, predictability of performance is at least as important as raw speed. Often, so is compactness of the resulting system. C++ was designed so that every language feature is usable in code under severe time and space constraints [Stroustrup,1994,§4.5]. Most applications have sections of code that are critical for acceptable performance. However, the largest amount of code is not in such sections. For most code, maintainability, ease of exten- sion, and ease of testing is key. C++’s support for these concerns has led to its widespread use where reliability is a must and in areas where requirements change significantly over time. Exam- ples are banking, trading, insurance, telecommunications, and military applications. For years, the central control of the U.S. long-distance telephone system has relied on C++ and every 800 call (that is, a call paid for by the called party) has been routed by a C++ program [Kamath,1993]. Many such applications are large and long-lived. As a result, stability, compatibility, and scalabil- ity have been constant concerns in the development of C++. Million-line C++ programs are not uncommon. Like C, C++ wasn’t specifically designed with numerical computation in mind. However, much numerical, scientific, and engineering computation is done in C++. A major reason for this is that traditional numerical work must often be combined with graphics and with computations relying on data structures that don’t fit into the traditional Fortran mold [Budge,1992] [Barton,1994]. Graph- ics and user interfaces are areas in which C++ is heavily used. Anyone who has used either an Apple Macintosh or a PC running Windows has indirectly used C++ because the primary user inter- faces of these systems are C++ programs. In addition, some of the most popular libraries support- ing X for UNIX are written in C++. Thus, C++ is a common choice for the vast number of applica- tions in which the user interface is a major part. All of this points to what may be C++’s greatest strength: its ability to be used effectively for applications that require work in a variety of application areas. It is quite common to find an appli- cation that involves local and wide-area networking, numerics, graphics, user interaction, and data- base access. Traditionally, such application areas have been considered distinct, and they have most often been served by distinct technical communities using a variety of programming lan- guages. However, C++ has been widely used in all of those areas. Furthermore, it is able to coexist with code fragments and programs written in other languages. C++ is widely used for teaching and research. This has surprised some who – correctly – point out that C++ isn’t the smallest or cleanest language ever designed. It is, however – clean enough for successful teaching of basic concepts, – realistic, efficient, and flexible enough for demanding projects,
    23. Use of C++ Section 1.5 13 – available enough for organizations and collaborations relying on diverse development and execution environments, – comprehensive enough to be a vehicle for teaching advanced concepts and techniques, and – commercial enough to be a vehicle for putting what is learned into non-academic use. C++ is a language that you can grow with. 1.6 C and C++ C was chosen as the base language for C++ because it [1] is versatile, terse, and relatively low-level; [2] is adequate for most systems programming tasks; [3] runs everywhere and on everything; and [4] fits into the UNIX programming environment. C has its problems, but a language designed from scratch would have some too, and we know C’s problems. Importantly, working with C enabled ‘‘C with Classes’’ to be a useful (if awkward) tool within months of the first thought of adding Simula-like classes to C. As C++ became more widely used, and as the facilities it provided over and above those of C became more significant, the question of whether to retain compatibility was raised again and again. Clearly some problems could be avoided if some of the C heritage was rejected (see, e.g., [Sethi,1981]). This was not done because [1] there are millions of lines of C code that might benefit from C++, provided that a complete rewrite from C to C++ were unnecessary; [2] there are millions of lines of library functions and utility software code written in C that could be used from/on C++ programs provided C++ were link-compatible with and syntacti- cally very similar to C; [3] there are hundreds of thousands of programmers who know C and therefore need only learn to use the new features of C++ and not relearn the basics; and [4] C++ and C will be used on the same systems by the same people for years, so the differ- ences should be either very large or very small so as to minimize mistakes and confusion. The definition of C++ has been revised to ensure that a construct that is both legal C and legal C++ has the same meaning in both languages (with a few minor exceptions; see §B.2). The C language has itself evolved, partly under the influence of the development of C++ [Rosler,1984]. The ANSI C standard [C,1990] contains a function declaration syntax borrowed from ‘‘C with Classes.’’ Borrowing works both ways. For example, the v oi d* pointer type was vo id invented for ANSI C and first implemented in C++. As promised in the first edition of this book, the definition of C++ has been reviewed to remove gratuitous incompatibilities; C++ is now more compatible with C than it was originally. The ideal was for C++ to be as close to ANSI C as possi- ble – but no closer [Koenig,1989]. One hundred percent compatibility was never a goal because that would compromise type safety and the smooth integration of user-defined and built-in types. Knowing C is not a prerequisite for learning C++. Programming in C encourages many tech- niques and tricks that are rendered unnecessary by C++ language features. For example, explicit type conversion (casting) is less frequently needed in C++ than it is in C (§1.6.1). However, good C programs tend to be C++ programs. For example, every program in Kernighan and Ritchie, The
    24. 14 Notes to the Reader Chapter 1 C Programming Language (2nd Edition) [Kernighan,1988], is a C++ program. Experience with any statically typed language will be a help when learning C++. 1.6.1 Suggestions for C Programmers The better one knows C, the harder it seems to be to avoid writing C++ in C style, thereby losing some of the potential benefits of C++. Please take a look at Appendix B, which describes the dif- ferences between C and C++. Here are a few pointers to the areas in which C++ has better ways of doing something than C has: [1] Macros are almost never necessary in C++. Use c on st (§5.4) or e nu m (§4.8) to define mani- co ns t en um fest constants, i nl in e (§7.1.1) to avoid function-calling overhead, t em pl at es (Chapter 13) to in li ne te mp la te specify families of functions and types, and n am es pa ce (§8.2) to avoid name clashes. na me sp ac es [2] Don’t declare a variable before you need it so that you can initialize it immediately. A declaration can occur anywhere a statement can (§6.3.1), in for-statement initializers (§6.3.3), and in conditions (§6.3.2.1). [3] Don’t use m al lo c(). The n ew operator (§6.2.6) does the same job better, and instead of ma ll oc ne w r ea ll oc re al lo c(), try a v ec to r (§3.8). ve ct or [4] Try to avoid v oi d*, pointer arithmetic, unions, and casts, except deep within the implemen- vo id tation of some function or class. In most cases, a cast is an indication of a design error. If you must use an explicit type conversion, try using one of the ‘‘new casts’’ (§6.2.7) for a more precise statement of what you are trying to do. [5] Minimize the use of arrays and C-style strings. The C++ standard library s tr in g (§3.5) and st ri ng v ec to r (§3.7.1) classes can often be used to simplify programming compared to traditional C ve ct or style. In general, try not to build yourself what has already been provided by the standard library. To obey C linkage conventions, a C++ function must be declared to have C linkage (§9.2.4). Most important, try thinking of a program as a set of interacting concepts represented as classes and objects, instead of as a bunch of data structures with functions twiddling their bits. 1.6.2 Suggestions for C++ Programmers By now, many people have been using C++ for a decade. Many more are using C++ in a single environment and have learned to live with the restrictions imposed by early compilers and first- generation libraries. Often, what an experienced C++ programmer has failed to notice over the years is not the introduction of new features as such, but rather the changes in relationships between features that make fundamental new programming techniques feasible. In other words, what you didn’t think of when first learning C++ or found impractical just might be a superior approach today. You find out only by re-examining the basics. Read through the chapters in order. If you already know the contents of a chapter, you can be through in minutes. If you don’t already know the contents, you’ll have learned something unex- pected. I learned a fair bit writing this book, and I suspect that hardly any C++ programmer knows every feature and technique presented. Furthermore, to use the language well, you need a perspec- tive that brings order to the set of features and techniques. Through its organization and examples, this book offers such a perspective.
    25. Thinking about Programming in C++ Section 1.7 15 1.7 Thinking about Programming in C++ Ideally, you approach the task of designing a program in three stages. First, you gain a clear under- standing of the problem (analysis), then you identify the key concepts involved in a solution (design), and finally you express that solution in a program (programming). However, the details of the problem and the concepts of the solution often become clearly understood only through the effort to express them in a program and trying to get it to run acceptably. This is where the choice of programming language matters. In most applications, there are concepts that are not easily represented as one of the fundamental types or as a function without associated data. Given such a concept, declare a class to represent it in the program. A C++ class is a type. That is, it specifies how objects of its class behave: how they are created, how they can be manipulated, and how they are destroyed. A class may also specify how objects are represented, although in the early stages of the design of a program that should not be the major concern. The key to writing good programs is to design classes so that each cleanly represents a single concept. Often, this means that you must focus on questions such as: How are objects of this class created? Can objects of this class be copied and/or destroyed? What opera- tions can be applied to such objects? If there are no good answers to such questions, the concept probably wasn’t ‘‘clean’’ in the first place. It might then be a good idea to think more about the problem and its proposed solution instead of immediately starting to ‘‘code around’’ the problems. The concepts that are easiest to deal with are the ones that have a traditional mathematical for- malism: numbers of all sorts, sets, geometric shapes, etc. Text-oriented I/O, strings, basic contain- ers, the fundamental algorithms on such containers, and some mathematical classes are part of the standard C++ library (Chapter 3, §16.1.2). In addition, a bewildering variety of libraries supporting general and domain-specific concepts are available. A concept does not exist in a vacuum; there are always clusters of related concepts. Organizing the relationship between classes in a program – that is, determining the exact relationship between the different concepts involved in a solution – is often harder than laying out the individual classes in the first place. The result had better not be a muddle in which every class (concept) depends on every other. Consider two classes, A and B. Relationships such as ‘‘A calls functions from B,’’ ‘‘A creates Bs,’’ and ‘‘A has a B member’’ seldom cause major problems, while relationships such as ‘‘A uses data from B’’ can typically be eliminated. One of the most powerful intellectual tools for managing complexity is hierarchical ordering, that is, organizing related concepts into a tree structure with the most general concept as the root. In C++, derived classes represent such structures. A program can often be organized as a set of trees or directed acyclic graphs of classes. That is, the programmer specifies a number of base classes, each with its own set of derived classes. Virtual functions (§2.5.5, §12.2.6) can often be used to define operations for the most general version of a concept (a base class). When necessary, the interpretation of these operations can be refined for particular special cases (derived classes). Sometimes even a directed acyclic graph seems insufficient for organizing the concepts of a program; some concepts seem to be inherently mutually dependent. In that case, we try to localize cyclic dependencies so that they do not affect the overall structure of the program. If you cannot eliminate or localize such mutual dependencies, then you are most likely in a predicament that no programming language can help you out of. Unless you can conceive of some easily stated rela- tionships between the basic concepts, the program is likely to become unmanageable.
    26. 16 Notes to the Reader Chapter 1 One of the best tools for untangling dependency graphs is the clean separation of interface and implementation. Abstract classes (§2.5.4, §12.3) are C++’s primary tool for doing that. Another form of commonality can be expressed through templates (§2.7, Chapter 13). A class template specifies a family of classes. For example, a list template specifies ‘‘list of T,’’ where ‘‘T’’ can be any type. Thus, a template is a mechanism for specifying how one type is generated given another type as an argument. The most common templates are container classes such as lists, vectors, and associative arrays (maps) and the fundamental algorithms using such containers. It is usually a mistake to express parameterization of a class and its associated functions with a type using inheritance. It is best done using templates. Remember that much programming can be simply and clearly done using only primitive types, data structures, plain functions, and a few library classes. The whole apparatus involved in defin- ing new types should not be used except when there is a real need. The question ‘‘How does one write good programs in C++?’’ is very similar to the question ‘‘How does one write good English prose?’’ There are two answers: ‘‘Know what you want to say’’ and ‘‘Practice. Imitate good writing.’’ Both appear to be as appropriate for C++ as they are for English – and as hard to follow. 1.8 Advice Here is a set of ‘‘rules’’ you might consider while learning C++. As you get more proficient you can evolve them into something suitable for your kind of applications and your style of program- ming. They are deliberately very simple, so they lack detail. Don’t take them too literally. To write a good program takes intelligence, taste, and patience. You are not going to get it right the first time. Experiment! [1] When you program, you create a concrete representation of the ideas in your solution to some problem. Let the structure of the program reflect those ideas as directly as possible: [a] If you can think of ‘‘it’’ as a separate idea, make it a class. [b] If you can think of ‘‘it’’ as a separate entity, make it an object of some class. [c] If two classes have a common interface, make that interface an abstract class. [d] If the implementations of two classes have something significant in common, make that commonality a base class. [e] If a class is a container of objects, make it a template. [f] If a function implements an algorithm for a container, make it a template function imple- menting the algorithm for a family of containers. [g] If a set of classes, templates, etc., are logically related, place them in a common namespace. [2] When you define either a class that does not implement either a mathematical entity like a matrix or a complex number or a low-level type such as a linked list: [a] Don’t use global data (use members). [b] Don’t use global functions. [c] Don’t use public data members. [d] Don’t use friends, except to avoid [a] or [c]. [e] Don’t put a ‘‘type field’’ in a class; use virtual functions. [f] Don’t use inline functions, except as a significant optimization.
    27. Section 1.8 Advice 17 More specific or detailed rules of thumb can be found in the ‘‘Advice’’ section of each chapter. Remember, this advice is only rough rules of thumb, not immutable laws. A piece of advice should be applied only ‘‘where reasonable.’’ There is no substitute for intelligence, experience, common sense, and good taste. I find rules of the form ‘‘never do this’’ unhelpful. Consequently, most advice is phrased as suggestions of what to do, while negative suggestions tend not to be phrased as absolute prohibi- tions. I know of no major feature of C++ that I have not seen put to good use. The ‘‘Advice’’ sec- tions do not contain explanations. Instead, each piece of advice is accompanied by a reference to the appropriate section of the book. Where negative advice is given, that section usually provides a suggested alternative. 1.8.1 References There are few direct references in the text, but here is a short list of books and papers that are men- tioned directly or indirectly. John J. Barton and Lee R. Nackman: Scientific and Engineering C++. [Barton,1994] Addison-Wesley. Reading, Mass. 1994. ISBN 0-201-53393-6. [Berg,1995] William Berg, Marshall Cline, and Mike Girou: Lessons Learned from the OS/400 OO Project. CACM. Vol. 38 No. 10. October 1995. [Booch,1994] Grady Booch: Object-Oriented Analysis and Design. Benjamin/Cummings. Menlo Park, Calif. 1994. ISBN 0-8053-5340-2. [Budge,1992] Kent Budge, J. S. Perry, and A. C. Robinson: High-Performance Scientific Computation using C++. Proc. USENIX C++ Conference. Portland, Oregon. August 1992. [C,1990] X3 Secretariat: Standard – The C Language. X3J11/90-013. ISO Standard ISO/IEC 9899. Computer and Business Equipment Manufacturers Association. Washington, DC, USA. [C++,1998] X3 Secretariat: International Standard – The C++ Language. X3J16-14882. Information Technology Council (NSITC). Washington, DC, USA. [Campbell,1987] Roy Campbell, et al.: The Design of a Multiprocessor Operating System. Proc. USENIX C++ Conference. Santa Fe, New Mexico. November 1987. [Coplien,1995] James O. Coplien and Douglas C. Schmidt (editors): Pattern Languages of Program Design. Addison-Wesley. Reading, Mass. 1995. ISBN 0-201- 60734-4. [Dahl,1970] O-J. Dahl, B. Myrhaug, and K. Nygaard: SIMULA Common Base Language. Norwegian Computing Center S-22. Oslo, Norway. 1970. [Dahl,1972] O-J. Dahl and C. A. R. Hoare: Hierarchical Program Construction in Struc- tured Programming. Academic Press, New York. 1972. Margaret A. Ellis and Bjarne Stroustrup: The Annotated C++ Reference Man- [Ellis,1989] ual. Addison-Wesley. Reading, Mass. 1990. ISBN 0-201-51459-1. [Gamma,1995] Erich Gamma, et al.: Design Patterns. Addison-Wesley. Reading, Mass. 1995. ISBN 0-201-63361-2. [Goldberg,1983] A. Goldberg and D. Robson: SMALLTALK-80 – The Language and Its Imple- mentation. Addison-Wesley. Reading, Mass. 1983.
    28. 18 Notes to the Reader Chapter 1 [Griswold,1970] R. E. Griswold, et al.: The Snobol4 Programming Language. Prentice-Hall. Englewood Cliffs, New Jersey. 1970. [Griswold,1983] R. E. Griswold and M. T. Griswold: The ICON Programming Language. Prentice-Hall. Englewood Cliffs, New Jersey. 1983. [Hamilton,1993] G. Hamilton and P. Kougiouris: The Spring Nucleus: A Microkernel for Objects. Proc. 1993 Summer USENIX Conference. USENIX. [Henricson,1997] Mats Henricson and Erik Nyquist: Industrial Strength C++: Rules and Recom- mendations. Prentice-Hall. Englewood Cliffs, New Jersey. 1997. ISBN 0- 13-120965-5. [Ichbiah,1979] Jean D. Ichbiah, et al.: Rationale for the Design of the ADA Programming Lan- guage. SIGPLAN Notices. Vol. 14 No. 6. June 1979. [Kamath,1993] Yogeesh H. Kamath, Ruth E. Smilan, and Jean G. Smith: Reaping Benefits with Object-Oriented Technology. AT&T Technical Journal. Vol. 72 No. 5. September/October 1993. [Kernighan,1978] Brian W. Kernighan and Dennis M. Ritchie: The C Programming Language. Prentice-Hall. Englewood Cliffs, New Jersey. 1978. [Kernighan,1988] Brian W. Kernighan and Dennis M. Ritchie: The C Programming Language (Second Edition). Prentice-Hall. Englewood Cliffs, New Jersey. 1988. ISBN 0-13-110362-8. Andrew Koenig and Bjarne Stroustrup: C++: As close to C as possible – but no [Koenig,1989] closer. The C++ Report. Vol. 1 No. 7. July 1989. Andrew Koenig and Barbara Moo: Ruminations on C++. Addison Wesley [Koenig,1997] Longman. Reading, Mass. 1997. ISBN 0-201-42339-1. [Knuth,1968] Donald Knuth: The Art of Computer Programming. Addison-Wesley. Read- ing, Mass. [Liskov,1979] Barbara Liskov et al.: Clu Reference Manual. MIT/LCS/TR-225. MIT Cam- bridge. Mass. 1979. Robert C. Martin: Designing Object-Oriented C++ Applications Using the [Martin,1995] Booch Method. Prentice-Hall. Englewood Cliffs, New Jersey. 1995. ISBN 0-13-203837-4. [Orwell,1949] George Orwell: 1984. Secker and Warburg. London. 1949. [Parrington,1995] Graham Parrington et al.: The Design and Implementation of Arjuna. Com- puter Systems. Vol. 8 No. 3. Summer 1995. [Richards,1980] Martin Richards and Colin Whitby-Strevens: BCPL – The Language and Its Compiler. Cambridge University Press, Cambridge. England. 1980. ISBN 0-521-21965-5. [Rosler,1984] L. Rosler: The Evolution of C – Past and Future. AT&T Bell Laboratories Technical Journal. Vol. 63 No. 8. Part 2. October 1984. [Rozier,1988] M. Rozier, et al.: CHORUS Distributed Operating Systems. Computing Sys- tems. Vol. 1 No. 4. Fall 1988. [Sethi,1981] Ravi Sethi: Uniform Syntax for Type Expressions and Declarations. Software Practice & Experience. Vol. 11. 1981. [Stepanov,1994] Alexander Stepanov and Meng Lee: The Standard Template Library. HP Labs Technical Report HPL-94-34 (R. 1). August, 1994.
    29. Section 1.8.1 References 19 [Stroustrup,1986] Bjarne Stroustrup: The C++ Programming Language. Addison-Wesley. Reading, Mass. 1986. ISBN 0-201-12078-X. [Stroustrup,1987] Bjarne Stroustrup and Jonathan Shopiro: A Set of C Classes for Co-Routine Style Programming. Proc. USENIX C++ Conference. Santa Fe, New Mexico. November 1987. [Stroustrup,1991] Bjarne Stroustrup: The C++ Programming Language (Second Edition). Addison-Wesley. Reading, Mass. 1991. ISBN 0-201-53992-6. [Stroustrup,1994] Bjarne Stroustrup: The Design and Evolution of C++. Addison-Wesley. Read- ing, Mass. 1994. ISBN 0-201-54330-3. [Tarjan,1983] Robert E. Tarjan: Data Structures and Network Algorithms. Society for Indus- trial and Applied Mathematics. Philadelphia, Penn. 1983. ISBN 0-898- 71187-8. [Unicode,1996] The Unicode Consortium: The Unicode Standard, Version 2.0. Addison- Wesley Developers Press. Reading, Mass. 1996. ISBN 0-201-48345-9. [UNIX,1985] UNIX Time-Sharing System: Programmer’s Manual. Research Version, Tenth Edition. AT&T Bell Laboratories, Murray Hill, New Jersey. February 1985. Gregory V. Wilson and Paul Lu (editors): Parallel Programming Using C++. [Wilson,1996] The MIT Press. Cambridge. Mass. 1996. ISBN 0-262-73118-5. .. .. ˚ [Wikstrom,1987] Ake Wikstrom: Functional Programming Using ML. Prentice-Hall. Engle- wood Cliffs, New Jersey. 1987. [Woodward,1974] P. M. Woodward and S. G. Bond: Algol 68-R Users Guide. Her Majesty’s Sta- tionery Office. London. England. 1974. References to books relating to design and larger software development issues can be found at the end of Chapter 23.
    30. 20 Notes to the Reader Chapter 1
    31. ________________________________________ ________________________________________________________________________________________________________________________________________________________________ 2 ________________________________________ ________________________________________________________________________________________________________________________________________________________________ A Tour of C++ The first thing we do, let´s kill all the language lawyers. – Henry VI, part II What is C++? — programming paradigms — procedural programming — modularity — separate compilation — exception handling — data abstraction — user-defined types — concrete types — abstract types — virtual functions — object-oriented programming — generic programming — containers — algorithms — language and programming — advice. 2.1 What is C++? [tour.intro] C++ is a general-purpose programming language with a bias towards systems programming that – is a better C, – supports data abstraction, – supports object-oriented programming, and – supports generic programming. This chapter explains what this means without going into the finer details of the language defini- tion. Its purpose is to give you a general overview of C++ and the key techniques for using it, not to provide you with the detailed information necessary to start programming in C++. If you find some parts of this chapter rough going, just ignore those parts and plow on. All will be explained in detail in later chapters. However, if you do skip part of this chapter, do yourself a favor by returning to it later. Detailed understanding of language features – even of all features of a language – cannot com- pensate for lack of an overall view of the language and the fundamental techniques for using it.
    32. A Tour of C++ 22 Chapter 2 2.2 Programming Paradigms [tour.paradigm] Object-oriented programming is a technique for programming – a paradigm for writing ‘‘good’’ programs for a set of problems. If the term ‘‘object-oriented programming language’’ means any- thing, it must mean a programming language that provides mechanisms that support the object- oriented style of programming well. There is an important distinction here. A language is said to support a style of programming if it provides facilities that make it convenient (reasonably easy, safe, and efficient) to use that style. A language does not support a technique if it takes exceptional effort or skill to write such pro- grams; it merely enables the technique to be used. For example, you can write structured programs in Fortran77 and object-oriented programs in C, but it is unnecessarily hard to do so because these languages do not directly support those techniques. Support for a paradigm comes not only in the obvious form of language facilities that allow direct use of the paradigm, but also in the more subtle form of compile-time and/or run-time checks against unintentional deviation from the paradigm. Type checking is the most obvious example of this; ambiguity detection and run-time checks are also used to extend linguistic support for para- digms. Extra-linguistic facilities such as libraries and programming environments can provide fur- ther support for paradigms. One language is not necessarily better than another because it possesses a feature the other does not. There are many examples to the contrary. The important issue is not so much what features a language possesses, but that the features it does possess are sufficient to support the desired pro- gramming styles in the desired application areas: [1] All features must be cleanly and elegantly integrated into the language. [2] It must be possible to use features in combination to achieve solutions that would otherwise require extra, separate features. [3] There should be as few spurious and ‘‘special-purpose’’ features as possible. [4] A feature’s implementation should not impose significant overheads on programs that do not require it. [5] A user should need to know only about the subset of the language explicitly used to write a program. The first principle is an appeal to aesthetics and logic. The next two are expressions of the ideal of minimalism. The last two can be summarized as ‘‘what you don’t know won’t hurt you.’’ C++ was designed to support data abstraction, object-oriented programming, and generic pro- gramming in addition to traditional C programming techniques under these constraints. It was not meant to force one particular programming style upon all users. The following sections consider some programming styles and the key language mechanisms supporting them. The presentation progresses through a series of techniques starting with procedu- ral programming and leading up to the use of class hierarchies in object-oriented programming and generic programming using templates. Each paradigm builds on its predecessors, each adds some- thing new to the C++ programmer’s toolbox, and each reflects a proven design approach. The presentation of language features is not exhaustive. The emphasis is on design approaches and ways of organizing programs rather than on language details. At this stage, it is far more important to gain an idea of what can be done using C++ than to understand exactly how it can be achieved.
    33. Section 2.3 Procedural Programming 23 2.3 Procedural Programming [tour.proc] The original programming paradigm is: Decide which procedures you want; use the best algorithms you can find. The focus is on the processing – the algorithm needed to perform the desired computation. Lan- guages support this paradigm by providing facilities for passing arguments to functions and return- ing values from functions. The literature related to this way of thinking is filled with discussion of ways to pass arguments, ways to distinguish different kinds of arguments, different kinds of func- tions (e.g., procedures, routines, and macros), etc. A typical example of ‘‘good style’’ is a square-root function. Given a double-precision floating-point argument, it produces a result. To do this, it performs a well-understood mathemati- cal computation: d ou bl e s qr t(d ou bl e a rg do ub le sq rt do ub le ar g) { // code for calculating a square root } v oi d f vo id f() { d ou bl e r oo t2 = s qr t(2 ; do ub le ro ot 2 sq rt 2) // ... } Curly braces, { }, express grouping in C++. Here, they indicate the start and end of the function bodies. The double slash, //, begins a comment that extends to the end of the line. The keyword v oi d indicates that a function does not return a value. vo id From the point of view of program organization, functions are used to create order in a maze of algorithms. The algorithms themselves are written using function calls and other language facili- ties. The following subsections present a thumb-nail sketch of C++’s most basic facilities for expressing computation. 2.3.1 Variables and Arithmetic [tour.var] Every name and every expression has a type that determines the operations that may be performed on it. For example, the declaration i nt i nc h; in t in ch specifies that i nc h is of type i nt that is, i nc h is an integer variable. in ch in t; in ch A declaration is a statement that introduces a name into the program. It specifies a type for that name. A type defines the proper use of a name or an expression. C++ offers a variety of fundamental types, which correspond directly to hardware facilities. For example:
    34. A Tour of C++ 24 Chapter 2 b oo l bo ol // Boolean, possible values are true and false c ha r ch ar // character, for example, ’a’, ’z’, and ’9’ i nt in t // integer, for example, 1, 42, and 1216 d ou bl e do ub le // double-precision floating-point number, for example, 3.14 and 299793.0 A c ha r variable is of the natural size to hold a character on a given machine (typically a byte), and ch ar an i nt variable is of the natural size for integer arithmetic on a given machine (typically a word). in t The arithmetic operators can be used for any combination of these types: // plus, both unary and binary + // minus, both unary and binary - // multiply * // divide / // remainder % So can the comparison operators: // equal == // not equal != // less than < // greater than > // less than or equal <= // greater than or equal >= In assignments and in arithmetic operations, C++ performs all meaningful conversions between the basic types so that they can be mixed freely: vo id so me _f un ct io n() v oi d s om e_ fu nc ti on // function that doesn’t return a value { d ou bl e d = 2 2; do ub le 2.2 // initialize floating-point number i nt i = 7 in t 7; // initialize integer d = d i; d+i // assign sum to d i = d i; d*i // assign product to i } As in C, = is the assignment operator and == tests equality. 2.3.2 Tests and Loops [tour.loop] C++ provides a conventional set of statements for expressing selection and looping. For example, here is a simple function that prompts the user and returns a Boolean indicating the response: b oo l a cc ep t() bo ol ac ce pt { c ou t << \"D o y ou w an t t o p ro ce ed (y o r n \\n co ut Do yo u wa nt to pr oc ee d y or n)?\\ n\"; // write question c ha r a ns we r = 0 ch ar an sw er 0; c in >> a ns we r; ci n an sw er // read answer i f (a ns we r == ´y if an sw er y´) r et ur n t ru e; re tu rn tr ue r et ur n f al se re tu rn fa ls e; }
    35. Section 2.3.2 Tests and Loops 25 The << operator (‘‘put to’’) is used as an output operator; c ou t is the standard output stream. The co ut >> operator (‘‘get from’’) is used as an input operator; c in is the standard input stream. The type of ci n the right-hand operand of >> determines what input is accepted and is the target of the input opera- tion. The \\ n character at the end of the output string represents a newline. \\n The example could be slightly improved by taking an ‘n’ answer into account: b oo l a cc ep t2 bo ol ac ce pt 2() { c ou t << \"D o y ou w an t t o p ro ce ed (y o r n \\n co ut Do yo u wa nt to pr oc ee d y or n)?\\ n\"; // write question c ha r a ns we r = 0 ch ar an sw er 0; c in >> a ns we r; ci n an sw er // read answer s wi tc h (a ns we r) { sw it ch an sw er c as e ´y ca se y´: r et ur n t ru e; re tu rn tr ue c as e ´n ca se n´: r et ur n f al se re tu rn fa ls e; d ef au lt de fa ul t: c ou t << \"I ll t ak e t ha t f or a n o.\\ n\"; co ut I´l l ta ke th at fo r no \\n r et ur n f al se re tu rn fa ls e; } } A switch-statement tests a value against a set of constants. The case constants must be distinct, and if the value tested does not match any of them, the d ef au lt is chosen. The programmer need not de fa ul t provide a d ef au lt de fa ul t. Few programs are written without loops. In this case, we might like to give the user a few tries: b oo l a cc ep t3 bo ol ac ce pt 3() { i nt t ri es = 1 in t tr ie s 1; w hi le (t ri es < 4 { wh il e tr ie s 4) c ou t << \"D o y ou w an t t o p ro ce ed (y o r n \\n co ut Do yo u wa nt to pr oc ee d y or n)?\\ n\"; // write question c ha r a ns we r = 0 ch ar an sw er 0; c in >> a ns we r; ci n an sw er // read answer s wi tc h (a ns we r) { sw it ch an sw er c as e ´y ca se y´: r et ur n t ru e; re tu rn tr ue c as e ´n ca se n´: r et ur n f al se re tu rn fa ls e; d ef au lt de fa ul t: c ou t << \"S or ry I d on t u nd er st an d t ha t.\\ n\"; co ut So rr y, do n´t un de rs ta nd th at \\n t ri es = t ri es + 1 tr ie s tr ie s 1; } } c ou t << \"I ll t ak e t ha t f or a n o.\\ n\"; co ut I´l l ta ke th at fo r no \\n r et ur n f al se re tu rn fa ls e; } The while-statement executes until its condition becomes f al se fa ls e.
    36. A Tour of C++ 26 Chapter 2 2.3.3 Pointers and Arrays [tour.ptr] An array can be declared like this: c ha r v 10 ; ch ar v[1 0] // array of 10 characters Similarly, a pointer can be declared like this: c ha r* p // pointer to character ch ar p; In declarations, [] means ‘‘array of’’ and * means ‘‘pointer to.’’ All arrays have 0 as their lower bound, so v has ten elements, v 0]...v 9]. A pointer variable can hold the address of an object of v[0 v[9 the appropriate type: p = &v 3]; v[3 // p points to v’s fourth element Unary & is the address-of operator. Consider copying ten elements from one array to another: v oi d a no th er _f un ct io n() vo id an ot he r_ fu nc ti on { i nt v 1[1 0]; in t v1 10 i nt v 2[1 0]; in t v2 10 // ... f or (i nt i 0; i 10 ++i v 1[i v2 i]; fo r in t i=0 i<1 0; i) v1 i]=v 2[i } This for-statement can be read as ‘‘set i to zero, while i is less than 1 0, copy the i element and 10 ith increment i When applied to an integer variable, the increment operator ++ simply adds 1 i.’’ 1. 2.4 Modular Programming [tour.module] Over the years, the emphasis in the design of programs has shifted from the design of procedures and toward the organization of data. Among other things, this reflects an increase in program size. A set of related procedures with the data they manipulate is often called a module. The program- ming paradigm becomes: Decide which modules you want; partition the program so that data is hidden within modules. This paradigm is also known as the data-hiding principle. Where there is no grouping of proce- dures with related data, the procedural programming style suffices. Also, the techniques for design- ing ‘‘good procedures’’ are now applied for each procedure in a module. The most common exam- ple of a module is the definition of a stack. The main problems that have to be solved are: [1] Provide a user interface for the stack (e.g., functions p us h() and p op pu sh po p()). [2] Ensure that the representation of the stack (e.g., an array of elements) can be accessed only through this user interface. [3] Ensure that the stack is initialized before its first use.
    37. Section 2.4 Modular Programming 27 C++ provides a mechanism for grouping related data, functions, etc., into separate namespaces. For example, the user interface of a S ta ck module could be declared and used like this: St ac k n am es pa ce S ta ck { na me sp ac e St ac k // interface v oi d p us h(c ha r); vo id pu sh ch ar c ha r p op ; ch ar po p() } v oi d f vo id f() { S ta ck :p us h(´c ; St ac k: pu sh c´) i f (S ta ck :p op if St ac k: po p() != ´c c´) e rr or im po ss ib le ; er ro r(\"i mp os si bl e\") } The S ta ck : qualification indicates that the p us h() and p op St ac k: pu sh po p() are those from the S ta ck name- St ac k space. Other uses of those names will not interfere or cause confusion. The definition of the S ta ck could be provided in a separately-compiled part of the program: St ac k n am es pa ce S ta ck { na me sp ac e St ac k // implementation c on st i nt m ax _s iz e = 2 00 co ns t in t ma x_ si ze 20 0; ch ar v[m ax _s iz e] c ha r v ma x_ si ze ; i nt t op = 0 in t to p 0; v oi d p us h(c ha r c { /* check for overflow and push c */ } vo id pu sh ch ar c) c ha r p op { /* check for underflow and pop */ } ch ar po p() } The key point about this S ta ck module is that the user code is insulated from the data representation St ac k of S ta ck by the code implementing S ta ck :p us h() and S ta ck :p op St ac k St ac k: pu sh St ac k: po p(). The user doesn’t need to know that the S ta ck is implemented using an array, and the implementation can be changed without St ac k affecting user code. Because data is only one of the things one might want to ‘‘hide,’’ the notion of data hiding is trivially extended to the notion of information hiding; that is, the names of functions, types, etc., can also be made local to a module. Consequently, C++ allows any declaration to be placed in a namespace (§8.2). This S ta ck module is one way of representing a stack. The following sections use a variety of St ac k stacks to illustrate different programming styles. 2.4.1 Separate Compilation [tour.comp] C++ supports C’s notion of separate compilation. This can be used to organize a program into a set of semi-independent fragments. Typically, we place the declarations that specify the interface to a module in a file with a name indicating its intended use. Thus, n am es pa ce S ta ck { na me sp ac e St ac k // interface v oi d p us h(c ha r); vo id pu sh ch ar c ha r p op ; ch ar po p() } would be placed in a file s ta ck h, and users will include that file, called a header file, like this: st ac k.h
    38. A Tour of C++ 28 Chapter 2 #i nc lu de \"s ta ck h\" in cl ud e st ac k.h // get the interface v oi d f vo id f() { S ta ck :p us h(´c ; St ac k: pu sh c´) i f (S ta ck :p op if St ac k: po p() != ´c c´) e rr or im po ss ib le ; er ro r(\"i mp os si bl e\") } To help the compiler ensure consistency, the file providing the implementation of the S ta ck module St ac k will also include the interface: #i nc lu de \"s ta ck h\" in cl ud e st ac k.h // get the interface n am es pa ce S ta ck { na me sp ac e St ac k // representation c on st i nt m ax _s iz e = 2 00 co ns t in t ma x_ si ze 20 0; ch ar v[m ax _s iz e] c ha r v ma x_ si ze ; i nt t op = 0 in t to p 0; } v oi d S ta ck :p us h(c ha r c { /* check for overflow and push c */ } vo id St ac k: pu sh ch ar c) c ha r S ta ck :p op { /* check for underflow and pop */ } ch ar St ac k: po p() The user code goes in a third file, say u se r.c The code in u se r.c and s ta ck c shares the stack us er c. us er c st ac k.c interface information presented in s ta ck h, but the two files are otherwise independent and can be st ac k.h separately compiled. Graphically, the program fragments can be represented like this: stack.h: . S ta ck i nt er fa ce St ac k in te rf ac e user.c: stack.c: . . . . #i nc lu de \" st ac k. h\" in cl ud e \"s ta ck .h \" #i nc lu de \" st ac k. h\" in cl ud e \"s ta ck .h \" u se s ta ck us e st ac k d ef in e s ta ck de fi ne st ac k Separate compilation is an issue in all real programs. It is not simply a concern in programs that present facilities, such as a S ta ck as modules. Strictly speaking, using separate compilation isn’t a St ac k, language issue; it is an issue of how best to take advantage of a particular language implementation. However, it is of great practical importance. The best approach is to maximize modularity, repre- sent that modularity logically through language features, and then exploit the modularity physically through files for effective separate compilation (Chapter 8, Chapter 9). 2.4.2 Exception Handling [tour.except] When a program is designed as a set of modules, error handling must be considered in light of these modules. Which module is responsible for handling what errors? Often, the module that detects an error doesn’t know what action to take. The recovery action depends on the module that invoked
    39. Section 2.4.2 Exception Handling 29 the operation rather than on the module that found the error while trying to perform the operation. As programs grow, and especially when libraries are used extensively, standards for handling errors (or, more generally, ‘‘exceptional circumstances’’) become important. Consider again the S ta ck example. What ought to be done when we try to p us h() one too St ac k pu sh many characters? The writer of the S ta ck module doesn’t know what the user would like to be St ac k done in this case, and the user cannot consistently detect the problem (if the user could, the over- flow wouldn’t happen in the first place). The solution is for the S ta ck implementer to detect the St ac k overflow and then tell the (unknown) user. The user can then take appropriate action. For exam- ple: n am es pa ce S ta ck { na me sp ac e St ac k // interface v oi d p us h(c ha r); vo id pu sh ch ar c ha r p op ; ch ar po p() c la ss O ve rf lo w { }; // type representing overflow exceptions cl as s Ov er fl ow } When detecting an overflow, S ta ck :p us h() can invoke the exception-handling code; that is, St ac k: pu sh ‘‘throw an O ve rf lo w exception:’’ Ov er fl ow v oi d S ta ck :p us h(c ha r c vo id St ac k: pu sh ch ar c) { i f (t op == m ax _s iz e) t hr ow O ve rf lo w(); if to p ma x_ si ze th ro w Ov er fl ow // push c } The t hr ow transfers control to a handler for exceptions of type S ta ck :O ve rf lo w in some function th ro w St ac k: Ov er fl ow that directly or indirectly called S ta ck :p us h(). To do that, the implementation will unwind the St ac k: pu sh function call stack as needed to get back to the context of that caller. Thus, the t hr ow acts as a mul- th ro w tilevel r et ur n. For example: re tu rn v oi d f vo id f() { // ... t ry { // exceptions here are handled by the handler defined below tr y w hi le (t ru e) S ta ck :p us h(´c ; wh il e tr ue St ac k: pu sh c´) } c at ch (S ta ck :O ve rf lo w) { ca tc h St ac k: Ov er fl ow // oops: stack overflow; take appropriate action } // ... } The w hi le loop will try to loop forever. Therefore, the c at ch wh il e ca tc h-clause providing a handler for S ta ck :O ve rf lo w will be entered after some call of S ta ck :p us h() causes a t hr ow St ac k: Ov er fl ow St ac k: pu sh th ro w. Use of the exception-handling mechanisms can make error handling more regular and readable. See §8.3 and Chapter 14 for further discussion and details.
    40. A Tour of C++ 30 Chapter 2 2.5 Data Abstraction [tour.da] Modularity is a fundamental aspect of all successful large programs. It remains a focus of all design discussions throughout this book. However, modules in the form described previously are not sufficient to express complex systems cleanly. Here, I first present a way of using modules to provide a form of user-defined types and then show how to overcome some problems with that approach by defining user-defined types directly. 2.5.1 Modules Defining Types [tour.types] Programming with modules leads to the centralization of all data of a type under the control of a type manager module. For example, if we wanted many stacks – rather than the single one pro- vided by the S ta ck module above – we could define a stack manager with an interface like this: St ac k n am es pa ce S ta ck { na me sp ac e St ac k s tr uc t R ep st ru ct Re p; // definition of stack layout is elsewhere t yp ed ef R ep s ta ck ty pe de f Re p& st ac k; s ta ck c re at e(); st ac k cr ea te // make a new stack v oi d d es tr oy st ac k s ; vo id de st ro y(s ta ck s) // delete s v oi d p us h(s ta ck s c ha r c ; vo id pu sh st ac k s, ch ar c) // push c onto s c ha r p op st ac k s ; ch ar po p(s ta ck s) // pop s } The declaration s tr uc t R ep st ru ct Re p; says that R ep is the name of a type, but it leaves the type to be defined later (§5.7). The declaration Re p t yp ed ef R ep s ta ck ty pe de f Re p& st ac k; gives the name s ta ck to a ‘‘reference to R ep (details in §5.5). The idea is that a stack is identified st ac k Re p’’ by its S ta ck :s ta ck and that further details are hidden from users. St ac k: st ac k A S ta ck :s ta ck acts much like a variable of a built-in type: St ac k: st ac k s tr uc t B ad _p op { }; st ru ct Ba d_ po p v oi d f vo id f() { S ta ck :s ta ck s 1 = S ta ck :c re at e(); St ac k: st ac k s1 St ac k: cr ea te // make a new stack S ta ck :s ta ck s 2 = S ta ck :c re at e(); St ac k: st ac k s2 St ac k: cr ea te // make another new stack S ta ck :p us h(s 1,´c ; St ac k: pu sh s1 c´) S ta ck :p us h(s 2,´k ; St ac k: pu sh s2 k´) c´) t hr ow B ad _p op ; i f (S ta ck :p op s1 != ´c if St ac k: po p(s 1) th ro w Ba d_ po p() k´) t hr ow B ad _p op ; i f (S ta ck :p op s2 != ´k if St ac k: po p(s 2) th ro w Ba d_ po p() S ta ck :d es tr oy s1 ; St ac k: de st ro y(s 1) S ta ck :d es tr oy s2 ; St ac k: de st ro y(s 2) }
    41. Section 2.5.1 Modules Defining Types 31 We could implement this S ta ck in several ways. It is important that a user doesn’t need to know St ac k how we do it. As long as we keep the interface unchanged, a user will not be affected if we decide to re-implement S ta ck St ac k. An implementation might preallocate a few stack representations and let S ta ck :c re at e() hand St ac k: cr ea te out a reference to an unused one. S ta ck :d es tr oy St ac k: de st ro y() could then mark a representation ‘‘unused’’ so that S ta ck :c re at e() can recycle it: St ac k: cr ea te n am es pa ce S ta ck { na me sp ac e St ac k // representation c on st i nt m ax _s iz e = 2 00 co ns t in t ma x_ si ze 20 0; s tr uc t R ep { st ru ct Re p ch ar v[m ax _s iz e] c ha r v ma x_ si ze ; i nt t op in t to p; }; c on st i nt m ax = 1 6; // maximum number of stacks co ns t in t ma x 16 R ep s ta ck s[m ax ; Re p st ac ks ma x] // preallocated stack representations b oo l u se d[m ax ; bo ol us ed ma x] // used[i] is true if stacks[i] is in use } v oi d S ta ck :p us h(s ta ck s c ha r c { /* check s for overflow and push c */ } vo id St ac k: pu sh st ac k s, ch ar c) c ha r S ta ck :p op st ac k s { /* check s for underflow and pop */ } ch ar St ac k: po p(s ta ck s) S ta ck :s ta ck S ta ck :c re at e() St ac k: st ac k St ac k: cr ea te { // pick an unused Rep, mark it used, initialize it, and return a reference to it } v oi d S ta ck :d es tr oy st ac k s { /* mark s unused */ } vo id St ac k: de st ro y(s ta ck s) What we have done is to wrap a set of interface functions around the representation type. How the resulting ‘‘stack type’’ behaves depends partly on how we defined these interface functions, partly on how we presented the representation type to the users of S ta ck and partly on the design of the St ac ks, representation type itself. This is often less than ideal. A significant problem is that the presentation of such ‘‘fake types’’ to the users can vary greatly depending on the details of the representation type – and users ought to be insulated from knowledge of the representation type. For example, had we chosen to use a more elaborate data structure to identify a stack, the rules for assignment and initialization of S ta ck :s ta ck would have changed dramatically. This may indeed be desirable at times. How- St ac k: st ac ks ever, it shows that we have simply moved the problem of providing convenient S ta ck from the St ac ks S ta ck module to the S ta ck :s ta ck representation type. St ac k St ac k: st ac k More fundamentally, user-defined types implemented through a module providing access to an implementation type don’t behave like built-in types and receive less and different support than do built-in types. For example, the time that a S ta ck :R ep can be used is controlled through St ac k: Re p S ta ck :c re at e() and S ta ck :d es tr oy rather than by the usual language rules. St ac k: cr ea te St ac k: de st ro y()
    42. A Tour of C++ 32 Chapter 2 2.5.2 User-Defined Types [tour.udt] C++ attacks this problem by allowing a user to directly define types that behave in (nearly) the same way as built-in types. Such a type is often called an abstract data type. I prefer the term user-defined type. A more reasonable definition of abstract data type would require a mathemati- cal ‘‘abstract’’ specification. Given such a specification, what are called types here would be con- crete examples of such truly abstract entities. The programming paradigm becomes: Decide which types you want; provide a full set of operations for each type. Where there is no need for more than one object of a type, the data-hiding programming style using modules suffices. Arithmetic types such as rational and complex numbers are common examples of user-defined types. Consider: c la ss c om pl ex { cl as s co mp le x d ou bl e r e, i m; do ub le re im p ub li c: pu bl ic c om pl ex do ub le r d ou bl e i { r e=r i m=i } co mp le x(d ou bl e r, do ub le i) re r; im i; // construct complex from two scalars c om pl ex do ub le r { r e=r i m=0 } co mp le x(d ou bl e r) re r; im 0; // construct complex from one scalar c om pl ex co mp le x() { r e = i m = 0 } re im 0; // default complex: (0,0) f ri en d fr ie nd c om pl ex co mp le x o pe ra to r+(c om pl ex c om pl ex ; op er at or co mp le x, co mp le x) f ri en d fr ie nd c om pl ex co mp le x o pe ra to r-(c om pl ex c om pl ex ; op er at or co mp le x, co mp le x) // binary f ri en d fr ie nd c om pl ex co mp le x o pe ra to r-(c om pl ex ; op er at or co mp le x) // unary f ri en d fr ie nd c om pl ex co mp le x o pe ra to r*(c om pl ex c om pl ex ; op er at or co mp le x, co mp le x) f ri en d fr ie nd c om pl ex co mp le x o pe ra to r/(c om pl ex c om pl ex ; op er at or co mp le x, co mp le x) f ri en d b oo l o pe ra to r==(c om pl ex c om pl ex ; fr ie nd bo ol op er at or co mp le x, co mp le x) // equal f ri en d b oo l o pe ra to r!=(c om pl ex c om pl ex ; fr ie nd bo ol op er at or co mp le x, co mp le x) // not equal // ... }; The declaration of class (that is, user-defined type) c om pl ex specifies the representation of a com- co mp le x plex number and the set of operations on a complex number. The representation is private; that is, r e and i m are accessible only to the functions specified in the declaration of class c om pl ex Such re im co mp le x. functions can be defined like this: c om pl ex o pe ra to r+(c om pl ex a 1, c om pl ex a 2) co mp le x op er at or co mp le x a1 co mp le x a2 { r et ur n c om pl ex a1 re a2 re a1 im a2 im ; re tu rn co mp le x(a 1.r e+a 2.r e,a 1.i m+a 2.i m) } A member function with the same name as its class is called a constructor. A constructor defines a way to initialize an object of its class. Class c om pl ex provides three constructors. One makes a co mp le x c om pl ex from a d ou bl e, another takes a pair of d ou bl es, and the third makes a c om pl ex with a co mp le x do ub le do ub le co mp le x default value. Class c om pl ex can be used like this: co mp le x
    43. Section 2.5.2 User-Defined Types 33 v oi d f co mp le x z vo id f(c om pl ex z) { c om pl ex a = 2 3; co mp le x 2.3 c om pl ex b = 1 a; co mp le x 1/a c om pl ex c = a b*c om pl ex 1,2 3); co mp le x a+b co mp le x(1 2.3 // ... i f (c != b c = -(b a)+2 b; if c b) b/a 2*b } The compiler converts operators involving c om pl ex numbers into appropriate function calls. For co mp le x example, c b means o pe ra to r!=(c b) and 1 a means o pe ra to r/(c om pl ex 1),a c!=b op er at or c,b 1/a op er at or co mp le x(1 a). Most, but not all, modules are better expressed as user-defined types. 2.5.3 Concrete Types [tour.concrete] User-defined types can be designed to meet a wide variety of needs. Consider a user-defined S ta ck St ac k type along the lines of the c om pl ex type. To make the example a bit more realistic, this S ta ck type co mp le x St ac k is defined to take its number of elements as an argument: c la ss S ta ck { cl as s St ac k c ha r* v ch ar v; i nt t op in t to p; i nt m ax _s iz e; in t ma x_ si ze p ub li c: pu bl ic c la ss U nd er fl ow { }; cl as s Un de rf lo w // used as exception c la ss O ve rf lo w { }; cl as s Ov er fl ow // used as exception c la ss B ad _s iz e { }; cl as s Ba d_ si ze // used as exception S ta ck in t s ; St ac k(i nt s) // constructor ~S ta ck ; St ac k() // destructor v oi d p us h(c ha r c ; vo id pu sh ch ar c) c ha r p op ; ch ar po p() }; The constructor S ta ck in t) will be called whenever an object of the class is created. This takes St ac k(i nt care of initialization. If any cleanup is needed when an object of the class goes out of scope, a com- plement to the constructor – called the destructor – can be declared: S ta ck :S ta ck in t s St ac k: St ac k(i nt s) // constructor { t op = 0 to p 0; i f (1 00 00 s) t hr ow B ad _s iz e(); if 10 00 0<s th ro w Ba d_ si ze m ax _s iz e = s ma x_ si ze s; v = n ew c ha r[s ; ne w ch ar s] // allocate elements on the free store (heap, dynamic store) } S ta ck :~S ta ck St ac k: St ac k() // destructor { d el et e[] v de le te v; // free the elements for possible reuse of their space (§6.2.6) }
    44. A Tour of C++ 34 Chapter 2 The constructor initializes a new S ta ck variable. To do so, it allocates some memory on the free St ac k store (also called the heap or dynamic store) using the n ew operator. The destructor cleans up by ne w freeing that memory. This is all done without intervention by users of S ta ck The users simply St ac ks. create and use S ta ck much as they would variables of built-in types. For example: St ac ks S ta ck s _v ar 1(1 0); St ac k s_ va r1 10 // global stack with 10 elements v oi d f St ac k& s _r ef i nt i vo id f(S ta ck s_ re f, in t i) // reference to Stack { S ta ck s _v ar 2(i ; St ac k s_ va r2 i) // local stack with i elements S ta ck s _p tr = n ew S ta ck 20 ; // pointer to Stack allocated on free store St ac k* s_ pt r ne w St ac k(2 0) s _v ar 1.p us h(´a ; s_ va r1 pu sh a´) s _v ar 2.p us h(´b ; s_ va r2 pu sh b´) s _r ef pu sh c´); s_ re f.p us h(´c s _p tr pu sh d´); s_ pt r->p us h(´d // ... } This S ta ck type obeys the same rules for naming, scope, allocation, lifetime, copying, etc., as does St ac k a built-in type such as i nt and c ha r. in t ch ar Naturally, the p us h() and p op member functions must also be defined somewhere: pu sh po p() v oi d S ta ck :p us h(c ha r c vo id St ac k: pu sh ch ar c) { i f (t op == m ax _s iz e) t hr ow O ve rf lo w(); if to p ma x_ si ze th ro w Ov er fl ow v to p] = c v[t op c; t op = t op + 1 to p to p 1; } c ha r S ta ck :p op ch ar St ac k: po p() { i f (t op == 0 t hr ow U nd er fl ow ; if to p 0) th ro w Un de rf lo w() t op = t op - 1 to p to p 1; r et ur n v to p]; re tu rn v[t op } Types such as c om pl ex and S ta ck are called concrete types, in contrast to abstract types, where the co mp le x St ac k interface more completely insulates a user from implementation details. 2.5.4 Abstract Types [tour.abstract] One property was lost in the transition from S ta ck as a ‘‘fake type’’ implemented by a module St ac k (§2.5.1) to a proper type (§2.5.3). The representation is not decoupled from the user interface; rather, it is a part of what would be included in a program fragment using S ta ck The representa- St ac ks. tion is private, and therefore accessible only through the member functions, but it is present. If it changes in any significant way, a user must recompile. This is the price to pay for having concrete types behave exactly like built-in types. In particular, we cannot have genuine local variables of a type without knowing the size of the type’s representation. For types that don’t change often, and where local variables provide much-needed clarity and efficiency, this is acceptable and often ideal. However, if we want to completely isolate users of a
    45. Section 2.5.4 Abstract Types 35 stack from changes to its implementation, this last S ta ck is insufficient. Then, the solution is to St ac k decouple the interface from the representation and give up genuine local variables. First, we define the interface: c la ss S ta ck { cl as s St ac k p ub li c: pu bl ic c la ss U nd er fl ow { }; cl as s Un de rf lo w // used as exception c la ss O ve rf lo w { }; cl as s Ov er fl ow // used as exception v ir tu al v oi d p us h(c ha r c = 0 vi rt ua l vo id pu sh ch ar c) 0; v ir tu al c ha r p op vi rt ua l ch ar po p() = 0 0; }; The word v ir tu al means ‘‘may be redefined later in a class derived from this one’’ in Simula and vi rt ua l C++. A class derived from S ta ck provides an implementation for the S ta ck interface. The curious St ac k St ac k =0 syntax says that some class derived from S ta ck must define the function. Thus, this S ta ck can 0 St ac k St ac k serve as the interface to any class that implements its p us h() and p op functions. pu sh po p() This S ta ck could be used like this: St ac k v oi d f St ac k& s _r ef vo id f(S ta ck s_ re f) { s _r ef pu sh c´); s_ re f.p us h(´c i f (s _r ef po p() != ´c c´) t hr ow b ad _s ta ck ; if s_ re f.p op th ro w ba d_ st ac k() } Note how f f() uses the S ta ck interface in complete ignorance of implementation details. A class St ac k that provides the interface to a variety of other classes is often called a polymorphic type. Not surprisingly, the implementation could consist of everything from the concrete class S ta ck St ac k that we left out of the interface S ta ck St ac k: c la ss A rr ay _s ta ck : p ub li c S ta ck { cl as s Ar ra y_ st ac k pu bl ic St ac k // Array_stack implements Stack c ha r* p ch ar p; i nt m ax _s iz e; in t ma x_ si ze i nt t op in t to p; p ub li c: pu bl ic A rr ay _s ta ck in t s ; Ar ra y_ st ac k(i nt s) ~A rr ay _s ta ck ; Ar ra y_ st ac k() v oi d p us h(c ha r c ; vo id pu sh ch ar c) c ha r p op ; ch ar po p() }; The ‘‘:p ub li c’’ can be read as ‘‘is derived from,’’ ‘‘implements,’’ and ‘‘is a subtype of.’’ pu bl ic For a function like f f() to use a S ta ck in complete ignorance of implementation details, some St ac k other function will have to make an object on which it can operate. For example: v oi d g vo id g() { A rr ay _s ta ck a s(2 00 ; Ar ra y_ st ac k as 20 0) f as ; f(a s) }
    46. A Tour of C++ 36 Chapter 2 Since f doesn’t know about A rr ay _s ta ck but only knows the S ta ck interface, it will work just as f() Ar ra y_ st ac ks St ac k well for a different implementation of a S ta ck For example: St ac k. cl as s Li st _s ta ck pu bl ic St ac k c la ss L is t_ st ac k : p ub li c S ta ck { // List_stack implements Stack l is t<c ha r> l c; li st ch ar lc // (standard library) list of characters (§3.7.3) p ub li c: pu bl ic Li st _s ta ck L is t_ st ac k() { } vo id pu sh ch ar c) lc pu sh _f ro nt c) v oi d p us h(c ha r c { l c.p us h_ fr on t(c ; } c ha r p op ; ch ar po p() }; ch ar Li st _s ta ck po p() c ha r L is t_ st ac k::p op { c ha r x = l c.f ro nt ; ch ar lc fr on t() // get first element l c.p op _f ro nt ; lc po p_ fr on t() // remove first element r et ur n x re tu rn x; } lc pu sh _f ro nt c) Here, the representation is a list of characters. The l c.p us h_ fr on t(c adds c as the first element of l c, the call l c.p op _f ro nt removes the first element, and l c.f ro nt denotes l c’s first element. lc lc po p_ fr on t() lc fr on t() lc Li st _s ta ck A function can create a L is t_ st ac k and have f use it: f() v oi d h vo id h() { Li st _s ta ck ls L is t_ st ac k l s; f ls ; f(l s) } 2.5.5 Virtual Functions [tour.virtual] How is the call s _s et po p() in f s_ se t.p op f() resolved to the right function definition? When f f() is called Li st _s ta ck po p() must be called. When f from h h(), L is t_ st ac k::p op f() is called from g g(), A rr ay _s ta ck :p op Ar ra y_ st ac k: po p() must be called. To achieve this resolution, a S ta ck object must contain St ac k information to indicate the function to be called at run-time. A common implementation technique is for the compiler to convert the name of a v ir tu al function into an index into a table of pointers to vi rt ua l functions. That table is usually called ‘‘a virtual function table’’ or simply, a v tb l. Each class with vt bl virtual functions has its own v tb l identifying its virtual functions. This can be represented graphi- vt bl cally like this: A rr ay _s ta ck o bj ec t: Ar ra y_ st ac k ob je ct : v.tb l: vt bl : . A rr ay _s ta ck pu sh . Ar ra y_ st ac k::p us h() p m ax _s iz e A rr ay _s ta ck po p() ma x_ si ze Ar ra y_ st ac k::p op t op to p Li st _s ta ck ob je ct : L is t_ st ac k o bj ec t: v.tb l: vt bl : . Li st _s ta ck pu sh . L is t_ st ac k::p us h() lc lc Li st _s ta ck po p() L is t_ st ac k::p op
    47. Section 2.5.5 Virtual Functions 37 The functions in the v tb l allow the object to be used correctly even when the size of the object and vt bl the layout of its data are unknown to the caller. All the caller needs to know is the location of the v tb l in a S ta ck and the index used for each virtual function. This virtual call mechanism can be vt bl St ac k made essentially as efficient as the ‘‘normal function call’’ mechanism. Its space overhead is one pointer in each object of a class with virtual functions plus one v tb l for each such class. vt bl 2.6 Object-Oriented Programming [tour.oop] Data abstraction is fundamental to good design and will remain a focus of design throughout this book. However, user-defined types by themselves are not flexible enough to serve our needs. This section first demonstrates a problem with simple user-defined data types and then shows how to overcome that problem by using class hierarchies. 2.6.1 Problems with Concrete Types [tour.problems] A concrete type, like a ‘‘fake type’’ defined through a module, defines a sort of black box. Once the black box has been defined, it does not really interact with the rest of the program. There is no way of adapting it to new uses except by modifying its definition. This situation can be ideal, but it can also lead to severe inflexibility. Consider defining a type S ha pe for use in a graphics system. Sh ap e Assume for the moment that the system has to support circles, triangles, and squares. Assume also that we have c la ss P oi nt /* ... */ }; cl as s Po in t{ c la ss C ol or /* ... */ }; cl as s Co lo r{ The /* and */ specify the beginning and end, respectively, of a comment. This comment notation can be used for multi-line comments and comments that end before the end of a line. We might define a shape like this: e nu m K in d { c ir cl e, t ri an gl e, s qu ar e }; en um Ki nd ci rc le tr ia ng le sq ua re // enumeration (§4.8) c la ss S ha pe { cl as s Sh ap e K in d k Ki nd k; // type field P oi nt c en te r; Po in t ce nt er C ol or c ol Co lo r co l; // ... p ub li c: pu bl ic v oi d d ra w(); vo id dr aw v oi d r ot at e(i nt ; vo id ro ta te in t) // ... }; The ‘‘type field’’ k is necessary to allow operations such as d ra w() and r ot at e() to determine dr aw ro ta te what kind of shape they are dealing with (in a Pascal-like language, one might use a variant record with tag k The function d ra w() might be defined like this: k). dr aw
    48. A Tour of C++ 38 Chapter 2 v oi d S ha pe :d ra w() vo id Sh ap e: dr aw { s wi tc h (k { sw it ch k) c as e c ir cl e: ca se ci rc le // draw a circle b re ak br ea k; c as e t ri an gl e: ca se tr ia ng le // draw a triangle b re ak br ea k; c as e s qu ar e: ca se sq ua re // draw a square b re ak br ea k; } } This is a mess. Functions such as d ra w() must ‘‘know about’’ all the kinds of shapes there are. dr aw Therefore, the code for any such function grows each time a new shape is added to the system. If we define a new shape, every operation on a shape must be examined and (possibly) modified. We are not able to add a new shape to a system unless we have access to the source code for every operation. Because adding a new shape involves ‘‘touching’’ the code of every important operation on shapes, doing so requires great skill and potentially introduces bugs into the code that handles other (older) shapes. The choice of representation of particular shapes can get severely cramped by the requirement that (at least some of) their representation must fit into the typically fixed-sized framework presented by the definition of the general type S ha pe Sh ap e. 2.6.2 Class Hierarchies [tour.hierarchies] The problem is that there is no distinction between the general properties of every shape (that is, a shape has a color, it can be drawn, etc.) and the properties of a specific kind of shape (a circle is a shape that has a radius, is drawn by a circle-drawing function, etc.). Expressing this distinction and taking advantage of it defines object-oriented programming. Languages with constructs that allow this distinction to be expressed and used support object-oriented programming. Other languages don’t. The inheritance mechanism (borrowed for C++ from Simula) provides a solution. First, we specify a class that defines the general properties of all shapes: c la ss S ha pe { cl as s Sh ap e P oi nt c en te r; Po in t ce nt er C ol or c ol Co lo r co l; // ... p ub li c: pu bl ic P oi nt w he re { r et ur n c en te r; } Po in t wh er e() re tu rn ce nt er v oi d m ov e(P oi nt t o) { c en te r = t o; /* ... */ d ra w(); } vo id mo ve Po in t to ce nt er to dr aw v ir tu al v oi d d ra w() = 0 vi rt ua l vo id dr aw 0; v ir tu al v oi d r ot at e(i nt a ng le = 0 vi rt ua l vo id ro ta te in t an gl e) 0; // ... };
    49. Section 2.6.2 Class Hierarchies 39 As in the abstract type S ta ck in §2.5.4, the functions for which the calling interface can be defined St ac k – but where the implementation cannot be defined yet – are v ir tu al In particular, the functions vi rt ua l. d ra w() and r ot at e() can be defined only for specific shapes, so they are declared v ir tu al dr aw ro ta te vi rt ua l. Given this definition, we can write general functions manipulating vectors of pointers to shapes: vo id ro ta te _a ll ve ct or Sh ap e*>& v i nt a ng le // rotate v’s elements angle degrees v oi d r ot at e_ al l(v ec to r<S ha pe v, in t an gl e) { f or (i nt i = 0 i v.s iz e(); ++i v i]->r ot at e(a ng le ; fo r in t 0; i<v si ze i) v[i ro ta te an gl e) } To define a particular shape, we must say that it is a shape and specify its particular properties (including the virtual functions): c la ss C ir cl e : p ub li c S ha pe { cl as s Ci rc le pu bl ic Sh ap e i nt r ad iu s; in t ra di us p ub li c: pu bl ic v oi d d ra w() { /* ... */ } vo id dr aw v oi d r ot at e(i nt {} // yes, the null function vo id ro ta te in t) }; In C++, class C ir cl e is said to be derived from class S ha pe and class S ha pe is said to be a base of Ci rc le Sh ap e, Sh ap e class C ir cl e. An alternative terminology calls C ir cl e and S ha pe subclass and superclass, respec- Ci rc le Ci rc le Sh ap e tively. The derived class is said to inherit members from its base class, so the use of base and derived classes is commonly referred to as inheritance. The programming paradigm is: Decide which classes you want; provide a full set of operations for each class; make commonality explicit by using inheritance. Where there is no such commonality, data abstraction suffices. The amount of commonality between types that can be exploited by using inheritance and virtual functions is the litmus test of the applicability of object-oriented programming to a problem. In some areas, such as interactive graphics, there is clearly enormous scope for object-oriented programming. In other areas, such as classical arithmetic types and computations based on them, there appears to be hardly any scope for more than data abstraction, and the facilities needed for the support of object-oriented programming seem unnecessary. Finding commonality among types in a system is not a trivial process. The amount of common- ality to be exploited is affected by the way the system is designed. When a system is designed – and even when the requirements for the system are written – commonality must be actively sought. Classes can be designed specifically as building blocks for other types, and existing classes can be examined to see if they exhibit similarities that can be exploited in a common base class. For attempts to explain what object-oriented programming is without recourse to specific pro- gramming language constructs, see [Kerr,1987] and [Booch,1994] in §23.6. Class hierarchies and abstract classes (§2.5.4) complement each other instead of being mutually exclusive (§12.5). In general, the paradigms listed here tend to be complementary and often
    50. A Tour of C++ 40 Chapter 2 mutually supportive. For example, classes and modules contain functions, while modules contain classes and functions. The experienced designer applies a variety of paradigms as need dictates. 2.7 Generic Programming [tour.generic] Someone who wants a stack is unlikely always to want a stack of characters. A stack is a general concept, independent of the notion of a character. Consequently, it ought to be represented inde- pendently. More generally, if an algorithm can be expressed independently of representation details and if it can be done so affordably and without logical contortions, it ought to be done so. The programming paradigm is: Decide which algorithms you want; parameterize them so that they work for a variety of suitable types and data structures. 2.7.1 Containers [tour.containers] We can generalize a stack-of-characters type to a stack-of-anything type by making it a template and replacing the specific type c ha r with a template parameter. For example: ch ar t em pl at e<c la ss T c la ss S ta ck { te mp la te cl as s T> cl as s St ac k Tv T* v; i nt m ax _s iz e; in t ma x_ si ze i nt t op in t to p; p ub li c: pu bl ic c la ss U nd er fl ow { }; cl as s Un de rf lo w c la ss O ve rf lo w { }; cl as s Ov er fl ow S ta ck in t s ; St ac k(i nt s) // constructor ~S ta ck ; St ac k() // destructor v oi d p us h(T ; vo id pu sh T) T p op ; po p() }; The t em pl at e<c la ss T prefix makes T a parameter of the declaration it prefixes. te mp la te cl as s T> The member functions might be defined similarly: t em pl at e<c la ss T v oi d S ta ck T>::p us h(T c te mp la te cl as s T> vo id St ac k<T pu sh T c) { i f (t op == m ax _s iz e) t hr ow O ve rf lo w(); if to p ma x_ si ze th ro w Ov er fl ow v to p] = c v[t op c; t op = t op + 1 to p to p 1; }
    51. Section 2.7.1 Containers 41 t em pl at e<c la ss T T S ta ck T>::p op te mp la te cl as s T> St ac k<T po p() { i f (t op == 0 t hr ow U nd er fl ow ; if to p 0) th ro w Un de rf lo w() t op = t op - 1 to p to p 1; r et ur n v to p]; re tu rn v[t op } Given these definitions, we can use stacks like this: S ta ck ch ar s c; St ac k<c ha r> sc // stack of characters S ta ck co mp le x> s cp lx St ac k<c om pl ex sc pl x; // stack of complex numbers S ta ck l is t<i nt > s li St ac k< li st in t> sl i; // stack of list of integers v oi d f vo id f() { s c.p us h(´c ; sc pu sh c´) c´) t hr ow B ad _p op ; i f (s c.p op != ´c if sc po p() th ro w Ba d_ po p() s cp lx pu sh co mp le x(1 2)); sc pl x.p us h(c om pl ex 1,2 co mp le x(1 2)) t hr ow B ad _p op ; i f (s cp lx po p() != c om pl ex 1,2 if sc pl x.p op th ro w Ba d_ po p() } Similarly, we can define lists, vectors, maps (that is, associative arrays), etc., as templates. A class holding a collection of elements of some type is commonly called a container class, or simply a container. Templates are a compile-time mechanism so that their use incurs no run-time overhead com- pared to ‘‘hand-written code.’’ 2.7.2 Generic Algorithms [tour.algorithms] The C++ standard library provides a variety of containers, and users can write their own (Chapter 3, Chapter 17, Chapter 18). Thus, we find that we can apply the generic programming paradigm once more to parameterize algorithms by containers. For example, we want to sort, copy, and search v ec to rs, l is ts, and arrays without having to write s or t(), c op y(), and s ea rc h() functions for each ve ct or li st so rt co py se ar ch container. We also don’t want to convert to a specific data structure accepted by a single sort func- tion. Therefore, we must find a generalized way of defining our containers that allows us to manip- ulate one without knowing exactly which kind of container it is. One approach, the approach taken for the containers and non-numerical algorithms in the C++ standard library (§3.8, Chapter 18) is to focus on the notion of a sequence and manipulate sequences through iterators. Here is a graphical representation of the notion of a sequence: begin end ..... . . elements: ... . . . . ..... A sequence has a beginning and an end. An iterator refers to an element, and provides an operation that makes the iterator refer to the next element of the sequence. The end of a sequence is an
    52. A Tour of C++ 42 Chapter 2 iterator that refers one beyond the last element of the sequence. The physical representation of ‘‘the end’’ may be a sentinel element, but it doesn’t have to be. In fact, the point is that this notion of sequences covers a wide variety of representations, including lists and arrays. We need some standard notation for operations such as ‘‘access an element through an iterator’’ and ‘‘make the iterator refer to the next element.’’ The obvious choices (once you get the idea) are to use the dereference operator * to mean ‘‘access an element through an iterator’’ and the incre- ment operator ++ to mean ‘‘make the iterator refer to the next element.’’ Given that, we can write code like this: t em pl at e<c la ss I n, c la ss O ut v oi d c op y(I n f ro m, I n t oo _f ar O ut t o) te mp la te cl as s In cl as s Ou t> vo id co py In fr om In to o_ fa r, Ou t to { w hi le (f ro m != t oo _f ar { wh il e fr om to o_ fa r) *t o = *f ro m; // copy element pointed to to fr om ++t o; to // next input ++f ro m; fr om // next output } } This copies any container for which we can define iterators with the right syntax and semantics. C++’s built-in, low-level array and pointer types have the right operations for that, so we can write c ha r v c1 20 0]; // array of 200 characters ch ar vc 1[2 00 c ha r v c2 50 0]; // array of 500 characters ch ar vc 2[5 00 v oi d f vo id f() { c op y(&v c1 0],&v c1 20 0],&v c2 0]); co py vc 1[0 vc 1[2 00 vc 2[0 } This copies v c1 from its first element until its last into v c2 starting at v c2 first element. vc 1 vc 2 vc 2’s All standard library containers (§16.3, Chapter 17) support this notion of iterators and sequences. Two template parameters I n and O ut are used to indicate the types of the source and the target In Ou t instead of a single argument. This was done because we often want to copy from one kind of con- tainer into another. For example: c om pl ex a c[2 00 ; co mp le x ac 20 0] v oi d g ve ct or co mp le x>& v c, l is t<c om pl ex l c) vo id g(v ec to r<c om pl ex vc li st co mp le x>& lc { c op y(&a c[0 ,&a c[2 00 ,l c.b eg in co py ac 0] ac 20 0] lc be gi n()); c op y(l c.b eg in ,l c.e nd ,v c.b eg in co py lc be gi n() lc en d() vc be gi n()); } This copies the array to the l is t and the l is t to the v ec to r. For a standard container, b eg in li st li st ve ct or be gi n() is an iterator pointing to the first element.
    53. Section 2.8 Postscript 43 2.8 Postscript [tour.post] No programming language is perfect. Fortunately, a programming language does not have to be perfect to be a good tool for building great systems. In fact, a general-purpose programming lan- guage cannot be perfect for all of the many tasks to which it is put. What is perfect for one task is often seriously flawed for another because perfection in one area implies specialization. Thus, C++ was designed to be a good tool for building a wide variety of systems and to allow a wide variety of ideas to be expressed directly. Not everything can be expressed directly using the built-in features of a language. In fact, that isn’t even the ideal. Language features exist to support a variety of programming styles and tech- niques. Consequently, the task of learning a language should focus on mastering the native and natural styles for that language – not on the understanding of every little detail of all the language features. In practical programming, there is little advantage in knowing the most obscure language fea- tures or for using the largest number of features. A single language feature in isolation is of little interest. Only in the context provided by techniques and by other features does the feature acquire meaning and interest. Thus, when reading the following chapters, please remember that the real purpose of examining the details of C++ is to be able to use them in concert to support good pro- gramming style in the context of sound designs. 2.9 Advice [tour.advice] [1] Don’t panic! All will become clear in time; §2.1. [2] You don’t have to know every detail of C++ to write good programs; §1.7. [3] Focus on programming techniques, not on language features; §2.1. .
    54. A Tour of C++ 44 Chapter 2
    55. ________________________________________ ________________________________________________________________________________________________________________________________________________________________ 3 ________________________________________ ________________________________________________________________________________________________________________________________________________________________ A Tour of the Standard Library Why waste time learning when ignorance is instantaneous? – Hobbes Standard libraries — output — strings — input — vectors — range checking — lists — maps — container overview — algorithms — iterators — I/O iterators — traversals and predicates — algorithms using member functions — algorithm overview — complex numbers — vector arithmetic— standard library overview — advice. 3.1 Introduction [tour2.lib] No significant program is written in just a bare programming language. First, a set of supporting libraries are developed. These then form the basis for further work. Continuing Chapter 2, this chapter gives a quick tour of key library facilities to give you an idea what can be done using C++ and its standard library. Useful library types, such as s tr in g, v ec to r, st ri ng ve ct or l is t, and m ap are presented as well as the most common ways of using them. Doing this allows me li st ma p, to give better examples and to set better exercises in the following chapters. As in Chapter 2, you are strongly encouraged not to be distracted or discouraged by an incomplete understanding of details. The purpose of this chapter is to give you a taste of what is to come and to convey an understanding of the simplest uses of the most useful library facilities. A more detailed introduc- tion to the standard library is given in §16.1.2. The standard library facilities described in this book are part of every complete C++ implemen- tation. In addition to the standard C++ library, most implementations offer ‘‘graphical user inter- face’’ systems, often referred to as GUIs or window systems, for interaction between a user and a program. Similarly, most application development environments provide ‘‘foundation libraries’’ that support corporate or industrial ‘‘standard’’ development and/or execution environments. I do not describe such systems and libraries. The intent is to provide a self-contained description of C++
    56. 46 A Tour of the Standard Library Chapter 3 as defined by the standard and to keep the examples portable, except where specifically noted. Nat- urally, a programmer is encouraged to explore the more extensive facilities available on most sys- tems, but that is left to exercises. 3.2 Hello, world! [tour2.hello] The minimal C++ program is i nt m ai n() { } in t ma in It defines a function called m ai n, which takes no arguments and does nothing. ma in Every C++ program must have a function named m ai n(). The program starts by executing that ma in function. The i nt value returned by m ai n(), if any, is the program’s return value to ‘‘the system.’’ in t ma in If no value is returned, the system will receive a value indicating successful completion. A nonzero value from m ai n() indicates failure. ma in Typically, a program produces some output. Here is a program that writes out H el lo w or ld He ll o, wo rl d!: #i nc lu de <i os tr ea m> in cl ud e io st re am i nt m ai n() in t ma in { s td :c ou t << \"H el lo w or ld \\n st d: co ut He ll o, wo rl d!\\ n\"; } The line #i nc lu de <i os tr ea m> instructs the compiler to include the declarations of the standard in cl ud e io st re am stream I/O facilities as found in i os tr ea m. Without these declarations, the expression io st re am s td :c ou t << \"H el lo w or ld \\n st d: co ut He ll o, wo rl d!\\ n\" would make no sense. The operator << (‘‘put to’’) writes its second argument onto its first. In this case, the string literal \"H el lo w or ld \\n is written onto the standard output stream s td :c ou t. A He ll o, wo rl d!\\ n\" st d: co ut string literal is a sequence of characters surrounded by double quotes. In a string literal, the back- slash character \\ followed by another character denotes a single special character. In this case, \\ n is \\n the newline character, so that the characters written are H el lo w or ld followed by a newline. He ll o, wo rl d! 3.3 The Standard Library Namespace [tour2.name] The standard library is defined in a namespace (§2.4, §8.2) called s td That is why I wrote st d. s td :c ou t rather than plain c ou t. I was being explicit about using the s ta nd ar d c ou t, rather than st d: co ut co ut st an da rd co ut some other c ou t. co ut Every standard library facility is provided through some standard header similar to <i os tr ea m>. io st re am For example: #i nc lu de st ri ng in cl ud e<s tr in g> #i nc lu de li st in cl ud e<l is t> This makes the standard s tr in g and l is t available. To use them, the s td : prefix can be used: st ri ng li st st d:
    57. Section 3.3 The Standard Library Namespace 47 s td :s tr in g s = \"F ou r l eg s G oo d; t wo l eg s B aa ad st d: st ri ng Fo ur le gs Go od tw o le gs Ba aa d!\"; s td :l is t<s td :s tr in g> s lo ga ns st d: li st st d: st ri ng sl og an s; For simplicity, I will rarely use the s td : prefix explicitly in examples. Neither will I always st d: #i nc lu de the necessary headers explicitly. To compile and run the program fragments here, you in cl ud e must #i nc lu de the appropriate headers (as listed in §3.7.5, §3.8.6, and Chapter 16). In addition, in cl ud e you must either use the s td : prefix or make every name from s td global (§8.2.3). For example: st d: st d #i nc lu de st ri ng in cl ud e<s tr in g> // make the standard string facilities accessible u si ng n am es pa ce s td us in g na me sp ac e st d; // make std names available without std:: prefix s tr in g s = \"I gn or an ce i s b li ss st ri ng Ig no ra nc e is bl is s!\"; // ok: string is std::string It is generally in poor taste to dump every name from a namespace into the global namespace. However, to keep short the program fragments used to illustrate language and library features, I omit repetitive #i nc lu de and s td : qualifications. In this book, I use the standard library almost in cl ud es st d: exclusively, so if a name from the standard library is used, it either is a use of what the standard offers or part of an explanation of how the standard facility might be defined. 3.4 Output [tour2.ostream] The iostream library defines output for every built-in type. Further, it is easy to define output of a user-defined type. By default, values output to c ou t are converted to a sequence of characters. For co ut example, v oi d f vo id f() { c ou t << 1 0; co ut 10 } will place the character 1 followed by the character 0 on the standard output stream. So will v oi d g vo id g() { i nt i = 1 0; in t 10 c ou t << i co ut i; } Output of different types can be combined in the obvious way: v oi d h in t i vo id h(i nt i) { c ou t << \"t he v al ue o f i i s \"; co ut th e va lu e of is c ou t << i co ut i; c ou t << ´\\ n´; co ut \\n } If i has the value 1 0, the output will be 10 t he v al ue o f i i s 1 0 th e va lu e of is 10
    58. 48 A Tour of the Standard Library Chapter 3 A character constant is a character enclosed in single quotes. Note that a character constant is out- put as a character rather than as a numerical value. For example, v oi d k vo id k() { c ou t << ´a co ut a´; c ou t << ´b co ut b´; c ou t << ´c co ut c´; } will output a bc ab c. People soon tire of repeating the name of the output stream when outputting several related items. Fortunately, the result of an output expression can itself be used for further output. For example: v oi d h 2(i nt i vo id h2 in t i) { c ou t << \"t he v al ue o f i i s \" << i << ´\\ n´; co ut th e va lu e of is \\n } This is equivalent to h h(). Streams are explained in more detail in Chapter 21. 3.5 Strings [tour2.string] The standard library provides a s tr in g type to complement the string literals used earlier. The st ri ng s tr in g type provides a variety of useful string operations, such as concatenation. For example: st ri ng s tr in g s 1 = \"H el lo st ri ng s1 He ll o\"; s tr in g s 2 = \"w or ld st ri ng s2 wo rl d\"; v oi d m 1() vo id m1 { s tr in g s 3 = s 1 + \", \" + s 2 + \"!\\ n\"; st ri ng s3 s1 s2 \\n c ou t << s 3; co ut s3 } Here, s 3 is initialized to the character sequence s3 H el lo w or ld He ll o, wo rl d! followed by a newline. Addition of strings means concatenation. You can add strings, string liter- als, and characters to a string. In many applications, the most common form of concatenation is adding something to the end of a string. This is directly supported by the += operation. For example: v oi d m 2(s tr in g& s 1, s tr in g& s 2) vo id m2 st ri ng s1 st ri ng s2 { s 1 = s 1 + ´\\ n´; // append newline s1 s1 \\n s 2 += ´\\ n´; s2 \\n // append newline }
    59. Section 3.5 Strings 49 The two ways of adding to the end of a string are semantically equivalent, but I prefer the latter because it is more concise and likely to be more efficiently implemented. Naturally, s tr in gs can be compared against each other and against string literals. For example: st ri ng s tr in g i nc an ta ti on st ri ng in ca nt at io n; v oi d r es po nd co ns t s tr in g& a ns we r) vo id re sp on d(c on st st ri ng an sw er { i f (a ns we r == i nc an ta ti on { if an sw er in ca nt at io n) // perform magic } e ls e i f (a ns we r == \"y es { el se if an sw er ye s\") // ... } // ... } The standard library string class is described in Chapter 20. Among other useful features, it pro- vides the ability to manipulate substrings. For example: s tr in g n am e = \"N ie ls S tr ou st ru p\"; st ri ng na me Ni el s St ro us tr up v oi d m 3() vo id m3 { s tr in g s = n am e.s ub st r(6 10 ; st ri ng na me su bs tr 6,1 0) // s = \"Stroustrup\" n am e.r ep la ce 0,5 Ni ch ol as ; na me re pl ac e(0 5,\"N ic ho la s\") // name becomes \"Nicholas Stroustrup\" } The s ub st r() operation returns a string that is a copy of the substring indicated by its arguments. su bs tr The first argument is an index into the string (a position), and the second argument is the length of the desired substring. Since indexing starts from 0 s gets the value S tr ou st ru p. 0, St ro us tr up The r ep la ce operation replaces a substring with a value. In this case, the substring starting at re pl ac e() 0 with length 5 is N ie ls it is replaced by N ic ho la s. Thus, the final value of n am e is N ic ho la s Ni el s; Ni ch ol as na me Ni ch ol as S tr ou st ru p. Note that the replacement string need not be the same size as the substring that it is St ro us tr up replacing. 3.5.1 C-Style Strings [tour2.cstring] A C-style string is a zero-terminated array of characters (§5.2.2). As shown, we can easily enter a C-style string into a s tr in g. To call functions that take C-style strings, we need to be able to extract st ri ng the value of a s tr in g in the form of a C-style string. The c _s tr st ri ng c_ st r() function does that (§20.4.1). For example, we can print the n am e using the C output function p ri nt f() (§21.8) like this: na me pr in tf v oi d f vo id f() { s\\ n\",n am e.c _s tr p ri nt f(\"n am e: %s \\n na me c_ st r()); pr in tf na me }
    60. 50 A Tour of the Standard Library Chapter 3 3.6 Input [tour2.istream] The standard library offers i st re am for input. Like o st re am i st re am deal with character string is tr ea ms os tr ea ms, is tr ea ms representations of built-in types and can easily be extended to cope with user-defined types. The operator >> (‘‘get from’’) is used as an input operator; c in is the standard input stream. ci n The type of the right-hand operand of >> determines what input is accepted and what is the target of the input operation. For example, v oi d f vo id f() { i nt i in t i; c in >> i // read an integer into i ci n i; d ou bl e d do ub le d; c in >> d // read a double-precision, floating-point number into d ci n d; } reads a number, such as 1 23 4, from the standard input into the integer variable i and a floating- 12 34 point number, such as 1 2.3 4e 5, into the double-precision, floating-point variable d 12 34 e5 d. Here is an example that performs inch-to-centimeter and centimeter-to-inch conversions. You input a number followed by a character indicating the unit: centimeters or inches. The program then outputs the corresponding value in the other unit: i nt m ai n() in t ma in { c on st f lo at f ac to r = 2 54 // 1 inch equals 2.54 cm co ns t fl oa t fa ct or 2.5 4; f lo at x i n, c m; fl oa t x, in cm c ha r c h = 0 ch ar ch 0; c ou t << \"e nt er l en gt h: \"; co ut en te r le ng th c in >> x ci n x; // read a floating-point number c in >> c h; ci n ch // read a suffix s wi tc h (c h) { sw it ch ch c as e ´i ca se i´: // inch in = x in x; c m = x fa ct or cm x*f ac to r; b re ak br ea k; c as e ´c ca se c´: // cm i n = x fa ct or in x/f ac to r; cm = x cm x; b re ak br ea k; d ef au lt de fa ul t: in = cm = 0 in cm 0; b re ak br ea k; } c ou t << i n << \" i n = \" << c m << \" c m\\ n\"; co ut in in cm cm \\n } The switch-statement tests a value against a set of constants. The break-statements are used to exit
    61. Section 3.6 Input 51 the switch-statement. The case constants must be distinct. If the value tested does not match any of them, the d ef au lt is chosen. The programmer need not provide a d ef au lt de fa ul t de fa ul t. Often, we want to read a sequence of characters. A convenient way of doing that is to read into a s tr in g. For example: st ri ng i nt m ai n() in t ma in { s tr in g s tr st ri ng st r; c ou t << \"P le as e e nt er y ou r n am e\\ n\"; co ut Pl ea se en te r yo ur na me \\n c in >> s tr ci n st r; c ou t << \"H el lo \" << s tr << \"!\\ n\"; co ut He ll o, st r \\n } If you type in E ri c Er ic the response is H el lo E ri c! He ll o, Er ic By default, a whitespace character (§5.2.2) such as a space terminates the read, so if you enter E ri c B lo od ax e Er ic Bl oo da xe pretending to be the ill-fated king of York, the response is still H el lo E ri c! He ll o, Er ic You can read a whole line using the g et li ne function. For example: ge tl in e() i nt m ai n() in t ma in { s tr in g s tr st ri ng st r; c ou t << \"P le as e e nt er y ou r n am e\\ n\"; co ut Pl ea se en te r yo ur na me \\n g et li ne ci n,s tr ; ge tl in e(c in st r) c ou t << \"H el lo \" << s tr << \"!\\ n\"; co ut He ll o, st r \\n } With this program, the input E ri c B lo od ax e Er ic Bl oo da xe yields the desired output: H el lo E ri c B lo od ax e! He ll o, Er ic Bl oo da xe The standard strings have the nice property of expanding to hold what you put in them, so if you enter a couple of megabytes of semicolons, the program will echo pages of semicolons back at you – unless your machine or operating system runs out of some critical resource first.
    62. 52 A Tour of the Standard Library Chapter 3 3.7 Containers [tour2.stl] Much computing involves creating collections of various forms of objects and then manipulating such collections. Reading characters into a string and printing out the string is a simple example. A class with the main purpose of holding objects is commonly called a container. Providing suit- able containers for a given task and supporting them with useful fundamental operations are impor- tant steps in the construction of any program. To illustrate the standard library’s most useful containers, consider a simple program for keep- ing names and telephone numbers. This is the kind of program for which different approaches appear ‘‘simple and obvious’’ to people of different backgrounds. 3.7.1 Vector [tour2.vector] For many C programmers, a built-in array of (name,number) pairs would seem to be a suitable starting point: s tr uc t E nt ry { st ru ct En tr y s tr in g n am e; st ri ng na me i nt n um be r; in t nu mb er }; E nt ry p ho ne _b oo k[1 00 0]; En tr y ph on e_ bo ok 10 00 v oi d p ri nt _e nt ry in t i vo id pr in t_ en tr y(i nt i) // simple use { c ou t << p ho ne _b oo k[i na me << ´ ´ << p ho ne _b oo k[i nu mb er << ´\\ n´; co ut ph on e_ bo ok i].n am e ph on e_ bo ok i].n um be r \\n } However, a built-in array has a fixed size. If we choose a large size, we waste space; if we choose a smaller size, the array will overflow. In either case, we will have to write low-level memory- management code. The standard library provides a v ec to r (§16.3) that takes care of that: ve ct or v ec to r<E nt ry p ho ne _b oo k(1 00 0); ve ct or En tr y> ph on e_ bo ok 10 00 v oi d p ri nt _e nt ry in t i vo id pr in t_ en tr y(i nt i) // simple use, exactly as for array { c ou t << p ho ne _b oo k[i na me << ´ ´ << p ho ne _b oo k[i nu mb er << ´\\ n´; co ut ph on e_ bo ok i].n am e ph on e_ bo ok i].n um be r \\n } v oi d a dd _e nt ri es in t n // increase size by n vo id ad d_ en tr ie s(i nt n) { p ho ne _b oo k.r es iz e(p ho ne _b oo k.s iz e()+n ; ph on e_ bo ok re si ze ph on e_ bo ok si ze n) } The v ec to r member function s iz e() gives the number of elements. ve ct or si ze Note the use of parentheses in the definition of p ho ne _b oo k. We made a single object of type ph on e_ bo ok v ec to r<E nt ry and supplied its initial size as an initializer. This is very different from declaring a ve ct or En tr y> built-in array: v ec to r<E nt ry b oo k(1 00 0); ve ct or En tr y> bo ok 10 00 // vector of 1000 elements v ec to r<E nt ry b oo ks 10 00 ; ve ct or En tr y> bo ok s[1 00 0] // 1000 empty vectors
    63. Section 3.7.1 Vector 53 Should you make the mistake of using [] where you meant () when declaring a v ec to r, your com- ve ct or piler will almost certainly catch the mistake and issue an error message when you try to use the v ec to r. ve ct or A v ec to r is a single object that can be assigned. For example: ve ct or v oi d f ve ct or En tr y>& v vo id f(v ec to r<E nt ry v) { v ec to r<E nt ry v 2 = p ho ne _b oo k; ve ct or En tr y> v2 ph on e_ bo ok v = v 2; v2 // ... } Assigning a v ec to r involves copying its elements. Thus, after the initialization and assignment in ve ct or f f(), v and v 2 each holds a separate copy of every E nt ry in the phone book. When a v ec to r holds v2 En tr y ve ct or many elements, such innocent-looking assignments and initializations can be prohibitively expen- sive. Where copying is undesirable, references or pointers should be used. 3.7.2 Range Checking [tour2.range] The standard library v ec to r does not provide range checking by default (§16.3.3). For example: ve ct or v oi d f vo id f() { i nt i = p ho ne _b oo k[1 00 1].n um be r; // 1001 is out of range in t ph on e_ bo ok 10 01 nu mb er // ... } The initialization is likely to place some random value in i rather than giving an error. This is undesirable, so I will use a simple range-checking adaptation of v ec to r, called V ec in the following ve ct or Ve c, chapters. A V ec is like a v ec to r, except that it throws an exception of type o ut _o f_ ra ng e if a sub- ou t_ of _r an ge Ve c ve ct or script is out of range. Techniques for implementing types such as V ec and for using exceptions effectively are dis- Ve c cussed in §11.12, §8.3, and Chapter 14. However, the definition here is sufficient for the examples in this book: t em pl at e<c la ss T c la ss V ec : p ub li c v ec to r<T { te mp la te cl as s T> cl as s Ve c pu bl ic ve ct or T> p ub li c: pu bl ic V ec Ve c() : v ec to r<T ve ct or T>() { } V ec in t s : v ec to r<T s) { } Ve c(i nt s) ve ct or T>(s T o pe ra to r[](i nt i { r et ur n a t(i ; } T& op er at or in t i) re tu rn at i) // range-checked c on st T o pe ra to r[](i nt i c on st { r et ur n a t(i ; } co ns t T& op er at or in t i) co ns t re tu rn at i) // range-checked }; The a t() operation is a v ec to r subscript operation that throws an exception of type o ut _o f_ ra ng e ou t_ of _r an ge at ve ct or if its argument is out of the v ec to r’s range (§16.3.3). ve ct or Returning to the problem of keeping names and telephone numbers, we can now use a V ec to Ve c ensure that out-of-range accesses are caught. For example: V ec En tr y> p ho ne _b oo k(1 00 0); Ve c<E nt ry ph on e_ bo ok 10 00
    64. 54 A Tour of the Standard Library Chapter 3 v oi d p ri nt _e nt ry in t i vo id pr in t_ en tr y(i nt i) // simple use, exactly as for vector { c ou t << p ho ne _b oo k[i na me << ´ ´ << p ho ne _b oo k[i nu mb er << ´\\ n´; co ut ph on e_ bo ok i].n am e ph on e_ bo ok i].n um be r \\n } An out-of-range access will throw an exception that the user can catch. For example: v oi d f vo id f() { t ry { tr y 0; i<1 00 00 i++) p ri nt _e nt ry i); f or (i nt i = 0 i 10 00 0; i fo r in t pr in t_ en tr y(i } c at ch (o ut _o f_ ra ng e) { ca tc h ou t_ of _r an ge c ou t << \"r an ge e rr or \\n co ut ra ng e er ro r\\ n\"; } } The exception will be thrown, and then caught, when p ho ne _b oo k[i is tried with i 10 00 ph on e_ bo ok i] i==1 00 0. If the user doesn’t catch this kind of exception, the program will terminate in a well-defined manner rather than proceeding or failing in an undefined manner. One way to minimize surprises from exceptions is to use a m ai n() with a try-block as its body: ma in i nt m ai n() in t ma in t ry { tr y // your code } c at ch (o ut _o f_ ra ng e) { ca tc h ou t_ of _r an ge c er r << \"r an ge e rr or \\n ce rr ra ng e er ro r\\ n\"; } c at ch (...) { ca tc h c er r << \"u nk no wn e xc ep ti on t hr ow n\\ n\"; ce rr un kn ow n ex ce pt io n th ro wn \\n } This provides default exception handlers so that if we fail to catch some exception, an error mes- sage is printed on the standard error-diagnostic output stream c er r (§21.2.1). ce rr 3.7.3 List [tour2.list] Insertion and deletion of phone book entries could be common. Therefore, a list could be more appropriate than a vector for representing a simple phone book. For example: l is t<E nt ry p ho ne _b oo k; li st En tr y> ph on e_ bo ok When we use a list, we tend not to access elements using subscripting the way we commonly do for vectors. Instead, we might search the list looking for an element with a given value. To do this, we take advantage of the fact that a l is t is a sequence as described in §3.8: li st v oi d p ri nt _e nt ry co ns t s tr in g& s vo id pr in t_ en tr y(c on st st ri ng s) { t yp ed ef l is t<E nt ry :c on st _i te ra to r L I; ty pe de f li st En tr y>: co ns t_ it er at or LI
    65. Section 3.7.3 List 55 f or (L I i = p ho ne _b oo k.b eg in ; i != p ho ne _b oo k.e nd ; ++i { fo r LI ph on e_ bo ok be gi n() ph on e_ bo ok en d() i) E nt ry e = *i // reference used as shorthand En tr y& i; i f (s == e na me c ou t << e na me << ´ ´ << e nu mb er << ´\\ n´; if s e.n am e) co ut e.n am e e.n um be r \\n } } The search for s starts at the beginning of the list and proceeds until either s is found or the end is reached. Every standard library container provides the functions b eg in and e nd be gi n() en d(), which return an iterator to the first and to one-past-the-last element, respectively (§16.3.2). Given an iterator i i, the next element is ++i Given an iterator i the element it refers to is *i i. i, i. A user need not know the exact type of the iterator for a standard container. That iterator type is part of the definition of the container and can be referred to by name. When we don’t need to mod- ify an element of the container, c on st _i te ra to r is the type we want. Otherwise, we use the plain co ns t_ it er at or i te ra to r type (§16.3.1). it er at or Adding elements to a l is t is easy: li st v oi d a dd _e nt ry En tr y& e l is t<E nt ry :i te ra to r i vo id ad d_ en tr y(E nt ry e, li st En tr y>: it er at or i) { p ho ne _b oo k.p us h_ fr on t(e ; ph on e_ bo ok pu sh _f ro nt e) // add at beginning p ho ne _b oo k.p us h_ ba ck e); ph on e_ bo ok pu sh _b ac k(e // add at end p ho ne _b oo k.i ns er t(i e); ph on e_ bo ok in se rt i,e // add before the element ‘i’ refers to } 3.7.4 Map [tour2.map] Writing code to look up a name in a list of (name,number) pairs is really quite tedious. In addition, a linear search is quite inefficient for all but the shortest lists. Other data structures directly support insertion, deletion, and searching based on values. In particular, the standard library provides the m ap type (§17.4.1). A m ap is a container of pairs of values. For example: ma p ma p m ap st ri ng in t> p ho ne _b oo k; ma p<s tr in g,i nt ph on e_ bo ok In other contexts, a m ap is known as an associative array or a dictionary. ma p When indexed by a value of its first type (called the key) a m ap returns the corresponding value ma p of the second type (called the value or the mapped type). For example: v oi d p ri nt _e nt ry co ns t s tr in g& s vo id pr in t_ en tr y(c on st st ri ng s) { i f (i nt i = p ho ne _b oo k[s c ou t << s << ´ ´ << i << ´\\ n´; if in t ph on e_ bo ok s]) co ut \\n } If no match was found for the key s a default value is returned from the p ho ne _b oo k. The default s, ph on e_ bo ok value for an integer type in a m ap is 0 Here, I assume that 0 isn’t a valid telephone number. ma p 0. 3.7.5 Standard Containers [tour2.stdcontainer] A m ap a l is t, and a v ec to r can each be used to represent a phone book. However, each has ma p, li st ve ct or strengths and weaknesses. For example, subscripting a v ec to r is cheap and easy. On the other ve ct or hand, inserting an element between two elements tends to be expensive. A l is t has exactly the li st
    66. 56 A Tour of the Standard Library Chapter 3 opposite properties. A m ap resembles a l is t of (key,value) pairs except that it is optimized for find- ma p li st ing values based on keys. The standard library provides some of the most general and useful container types to allow the programmer to select a container that best serves the needs of an application: _________________________________________________________________ ________________________________________________________________ _ _ ________________________________________________________________ Standard Container Summary ve ct or <T >  v ec to r< T> A variable-sized vector (§16.3)  li st <T >  l is t< T>  A doubly-linked list (§17.2.2)  q ue ue <T >  qu eu e< T> A queue (§17.3.2)  s ta ck <T >  st ac k< T> A stack (§17.3.1)  d eq ue <T >  de qu e< T> A double-ended queue (§17.2.3)   pr io ri ty _q ue ue <T >  p ri or it y_ qu eu e< T> A queue sorted by value (§17.3.3)   s et <T >  se t< T> A set (§17.4.3)  m ul ti se t< T> mu lt is et <T > A set in which a value can occur many times (§17.4.4)   m ap <k ey ,v al >  ma p< ke y, va l> An associative array (§17.4.1)  m ul ti ma p< ke y, va l> A map in which a key can occur many times (§17.4.2)  _mu lt im ap <k ey ,v al > ________________________________________________________________ The standard containers are presented in §16.2, §16.3, and Chapter 17. The containers are defined in namespace s td and presented in headers <v ec to r>, <l is t>, <m ap etc. (§16.2). st d ve ct or li st ma p>, The standard containers and their basic operations are designed to be similar from a notational point of view. Furthermore, the meanings of the operations are equivalent for the various contain- pu sh _b ac k() can ers. In general, basic operations apply to every kind of container. For example, p us h_ ba ck be used (reasonably efficiently) to add elements to the end of a v ec to r as well as for a l is t, and ve ct or li st every container has a s iz e() member function that returns its number of elements. si ze This notational and semantic uniformity enables programmers to provide new container types that can be used in a very similar manner to the standard ones. The range-checked vector, V ec Ve c ha sh _m ap (§3.7.2), is an example of that. Chapter 17 demonstrates how a h as h_ ma p can be added to the framework. The uniformity of container interfaces also allows us to specify algorithms indepen- dently of individual container types. 3.8 Algorithms [tour2.algorithms] A data structure, such as a list or a vector, is not very useful on its own. To use one, we need oper- ations for basic access such as adding and removing elements. Furthermore, we rarely just store objects in a container. We sort them, print them, extract subsets, remove elements, search for objects, etc. Consequently, the standard library provides the most common algorithms for contain- ers in addition to providing the most common container types. For example, the following sorts a v ec to r and places a copy of each unique v ec to r element on a l is t: ve ct or ve ct or li st v oi d f ve ct or En tr y>& v e, l is t<E nt ry l e) vo id f(v ec to r<E nt ry ve li st En tr y>& le { s or t(v e.b eg in ,v e.e nd so rt ve be gi n() ve en d()); un iq ue _c op y(v e.b eg in u ni qu e_ co py ve be gi n(),v e.e nd ,l e.b eg in ve en d() le be gi n()); }
    67. Section 3.8 Algorithms 57 The standard algorithms are described in Chapter 18. They are expressed in terms of sequences of elements (§2.7.2). A sequence is represented by a pair of iterators specifying the first element and the one-beyond-the-last element. In the example, s or t() sorts the sequence from v e.b eg in so rt ve be gi n() to v e.e nd ve en d() – which just happens to be all the elements of a v ec to r. For writing, you need only to ve ct or specify the first element to be written. If more than one element is written, the elements following that initial element will be overwritten. If we wanted to add the new elements to the end of a container, we could have written: v oi d f ve ct or En tr y>& v e, l is t<E nt ry l e) vo id f(v ec to r<E nt ry ve li st En tr y>& le { s or t(v e.b eg in ,v e.e nd so rt ve be gi n() ve en d()); un iq ue _c op y(v e.b eg in ve en d() ba ck _i ns er te r(l e)) u ni qu e_ co py ve be gi n(),v e.e nd ,b ac k_ in se rt er le ; // append to le } ba ck _i ns er te r() adds elements at the end of a container, extending the container to make room A b ac k_ in se rt er for them (§19.2.4). C programmers will appreciate that the standard containers plus ba ck _i ns er te r()s eliminate the need to use error-prone, explicit C-style memory management b ac k_ in se rt er ba ck _i ns er te r() when appending can lead to using r ea ll oc re al lo c() (§16.3.5). Forgetting to use a b ac k_ in se rt er errors. For example: v oi d f li st En tr y>& v e, v ec to r<E nt ry vo id f(l is t<E nt ry ve ve ct or En tr y>& l e) le { c op y(v e.b eg in ,v e.e nd ,l e); co py ve be gi n() ve en d() le // error: le not an iterator c op y(v e.b eg in ,v e.e nd ,l e.e nd co py ve be gi n() ve en d() le en d()); // bad: writes beyond the end c op y(v e.b eg in ,v e.e nd ,l e.b eg in co py ve be gi n() ve en d() le be gi n()); // overwrite elements } 3.8.1 Use of Iterators [tour2.iteruse] When you first encounter a container, a few iterators referring to useful elements can be obtained; b eg in be gi n() and e nd en d() are the best examples of this. In addition, many algorithms return iterators. For example, the standard algorithm f in d looks for a value in a sequence and returns an iterator to fi nd the element found. Using f in d, we can write a function that counts the number of occurrences of a fi nd character in a s tr in g: st ri ng i nt c ou nt co ns t s tr in g& s c ha r c in t co un t(c on st st ri ng s, ch ar c) { s tr in g::c on st _i te ra to r i = f in d(s be gi n(),s en d(),c ; st ri ng co ns t_ it er at or fi nd s.b eg in s.e nd c) i nt n = 0 in t 0; w hi le (i != s en d()) { wh il e i s.e nd n; ++n i = f in d(i 1,s en d(),c ; fi nd i+1 s.e nd c) } r et ur n n re tu rn n; } The f in d algorithm returns an iterator to the first occurrence of a value in a sequence or the one- fi nd past-the-end iterator. Consider what happens for a simple call of c ou nt co un t:
    68. 58 A Tour of the Standard Library Chapter 3 v oi d f vo id f() { s tr in g m = \"M ar y h ad a l it tl e l am b\"; st ri ng Ma ry ha d li tt le la mb i nt a _c ou nt = c ou nt m,´a ; in t a_ co un t co un t(m a´) } The first call to f in d() finds the ´a in M ar y. Thus, the iterator points to that character and not to fi nd a´ Ma ry s en d(), so we enter the loop. In the loop, we start the search at i 1; that is, we start one past s.e nd i+1 where we found the ´a We then loop finding the other three ´a a´. a´s. That done, f in d() reaches fi nd the end and returns s en d() so that the condition i s.e nd fails and we exit the loop. s.e nd i!=s en d() That call of c ou nt could be graphically represented like this: co un t() ..... . . Ma r y had a l i t t l e l amb . . . . ..... The arrows indicate the initial, intermediate, and final values of the iterator i i. Naturally, the f in d algorithm will work equivalently on every standard container. Conse- fi nd quently, we could generalize the c ou nt function in the same way: co un t() t em pl at e<c la ss C c la ss T i nt c ou nt co ns t C v T v al te mp la te cl as s C, cl as s T> in t co un t(c on st C& v, va l) { t yp en am e C :c on st _i te ra to r i = f in d(v be gi n(),v en d(),v al ; // \"typename;\" see §C.13.5 ty pe na me C: co ns t_ it er at or fi nd v.b eg in v.e nd va l) i nt n = 0 in t 0; w hi le (i != v en d()) { wh il e i v.e nd n; ++n ++i // skip past the element we just found i; i = f in d(i v.e nd ,v al ; fi nd i,v en d() va l) } r et ur n n re tu rn n; } This works, so we can say: v oi d f li st co mp le x>& l c, v ec to r<s tr in g>& v c, s tr in g s vo id f(l is t<c om pl ex lc ve ct or st ri ng vc st ri ng s) { i nt i 1 = c ou nt lc co mp le x(1 3)); in t i1 co un t(l c,c om pl ex 1,3 i nt i 2 = c ou nt vc Ch ry si pp us ; in t i2 co un t(v c,\"C hr ys ip pu s\") i nt i 3 = c ou nt s,´x ; in t i3 co un t(s x´) } However, we don’t have to define a c ou nt template. Counting occurrences of an element is so gen- co un t erally useful that the standard library provides that algorithm. To be fully general, the standard library c ou nt takes a sequence as its argument, rather than a container, so we would say: co un t
    69. Section 3.8.1 Use of Iterators 59 v oi d f li st co mp le x>& l c, v ec to r<s tr in g>& v s, s tr in g s vo id f(l is t<c om pl ex lc ve ct or st ri ng vs st ri ng s) { i nt i 1 = c ou nt lc be gi n(),l c.e nd ,c om pl ex 1,3 ; in t i1 co un t(l c.b eg in lc en d() co mp le x(1 3)) i nt i 2 = c ou nt vs be gi n(),v s.e nd ,\"D io ge ne s\"); in t i2 co un t(v s.b eg in vs en d() Di og en es i nt i 3 = c ou nt s.b eg in ,s en d(),´x ; in t i3 co un t(s be gi n() s.e nd x´) } The use of a sequence allows us to use c ou nt for a built-in array and also to count parts of a con- co un t tainer. For example: v oi d g ch ar c s[], i nt s z) vo id g(c ha r cs in t sz { i nt i 1 = c ou nt cs 0],&c s[s z],´z ; in t i1 co un t(&c s[0 cs sz z´) // ’z’s in array i nt i 2 = c ou nt cs 0],&c s[s z/2 ,´z ; in t i2 co un t(&c s[0 cs sz 2] z´) // ’z’s in first half of array } 3.8.2 Iterator Types [tour2.iter] What are iterators really? Any particular iterator is an object of some type. There are, however, many different iterator types because an iterator needs to hold the information necessary for doing its job for a particular container type. These iterator types can be as different as the containers and the specialized needs they serve. For example, a v ec to r’s iterator is most likely an ordinary pointer ve ct or because a pointer is quite a reasonable way of referring to an element of a v ec to r: ve ct or iterator: p vector: P i e t He i n Alternatively, a v ec to r iterator could be implemented as a pointer to the v ec to r plus an index: ve ct or ve ct or iterator: (start == p, position == 3) ............. vector: P i e t He i n Using such an iterator would allow range checking (§19.3). A list iterator must be something more complicated than a simple pointer to an element because an element of a list in general does not know where the next element of that list is. Thus, a list iter- ator might be a pointer to a link:
    70. 60 A Tour of the Standard Library Chapter 3 iterator: p list: link link link link ... elements: P i e t What is common for all iterators is their semantics and the naming of their operations. For exam- ple, applying ++ to any iterator yields an iterator that refers to the next element. Similarly, * yields the element to which the iterator refers. In fact, any object that obeys a few simple rules like these is an iterator (§19.2.1). Furthermore, users rarely need to know the type of a specific iterator; each container ‘‘knows’’ its iterator types and makes them available under the conventional names i te ra - it er a- t or and c on st _i te ra to r. For example, l is t<E nt ry :i te ra to r is the general iterator type for to r co ns t_ it er at or li st En tr y>: it er at or l is t<E nt ry I rarely have to worry about the details of how that type is defined. li st En tr y>. 3.8.3 Iterators and I/O [tour2.ioiterators] Iterators are a general and useful concept for dealing with sequences of elements in containers. However, containers are not the only place where we find sequences of elements. For example, an input stream produces a sequence of values and we write a sequence of values to an output stream. Consequently, the notion of iterators can be usefully applied to input and output. To make an o st re am _i te ra to r, we need to specify which stream will be used and the type of os tr ea m_ it er at or objects written to it. For example, we can define an iterator that refers to the standard output stream, c ou t: co ut o st re am _i te ra to r<s tr in g> o o(c ou t); os tr ea m_ it er at or st ri ng oo co ut The effect of assigning to *o o is to write the assigned value to c ou t. For example: oo co ut i nt m ai n() in t ma in { // meaning cout << \"Hello, \" *o o = \"H el lo \"; oo He ll o, ++o o; oo // meaning cout << \"world!\\n\" *o o = \"w or ld \\n oo wo rl d!\\ n\"; } This is yet another way of writing the canonical message to standard output. The ++o o is done to oo mimic writing into an array through a pointer. This way wouldn’t be my first choice for that simple task, but the utility of treating output as a write-only container will soon be obvious – if it isn’t already. Similarly, an i st re am _i te ra to r is something that allows us to treat an input stream as a read- is tr ea m_ it er at or only container. Again, we must specify the stream to be used and the type of values expected: i st re am _i te ra to r<s tr in g> i i(c in ; is tr ea m_ it er at or st ri ng ii ci n) Because input iterators invariably appear in pairs representing a sequence, we must provide an
    71. Section 3.8.3 Iterators and I/O 61 i st re am _i te ra to r to indicate the end of input. This is the default i st re am _i te ra to r: is tr ea m_ it er at or is tr ea m_ it er at or i st re am _i te ra to r<s tr in g> e os is tr ea m_ it er at or st ri ng eo s; We could now read H el lo w or ld from input and write it out again like this: He ll o, wo rl d! i nt m ai n() in t ma in { s tr in g s 1 = *i i; st ri ng s1 ii ++i i; ii s tr in g s 2 = *i i; st ri ng s2 ii c ou t << s 1 << ´ ´ << s 2 << ´\\ n´; co ut s1 s2 \\n } Actually, i st re am _i te ra to rs and o st re am _i te ra to rs are not meant to be used directly. Instead, they is tr ea m_ it er at or os tr ea m_ it er at or are typically provided as arguments to algorithms. For example, we can write a simple program to read a file, sort the words read, eliminate duplicates, and write the result to another file: i nt m ai n() in t ma in { s tr in g f ro m, t o; st ri ng fr om to c in >> f ro m >> t o; ci n fr om to // get source and target file names i fs tr ea m i s(f ro m.c _s tr if st re am is fr om c_ st r()); // input stream (c_str(); see §3.5) i st re am _i te ra to r<s tr in g> i i(i s); is tr ea m_ it er at or st ri ng ii is // input iterator for stream i st re am _i te ra to r<s tr in g> e os is tr ea m_ it er at or st ri ng eo s; // input sentinel v ec to r<s tr in g> b ii eo s); ve ct or st ri ng b(i i,e os // b is a vector initialized from input s or t(b be gi n(),b en d()); so rt b.b eg in b.e nd // sort the buffer o fs tr ea m o s(t o.c _s tr of st re am os to c_ st r()); // output stream o st re am _i te ra to r<s tr in g> o o(o s,\"\\ n\"); os tr ea m_ it er at or st ri ng oo os \\n // output iterator for stream un iq ue _c op y(b be gi n() b.e nd u ni qu e_ co py b.b eg in ,b en d(),o o); oo // copy buffer to output, // discard replicated values r et ur n !i s.e of re tu rn is eo f() && !o s; os // return error state (§3.2, §21.3.3) } An i fs tr ea m is an i st re am that can be attached to a file, and an o fs tr ea m is an o st re am that can be if st re am is tr ea m of st re am os tr ea m attached to a file. The o st re am _i te ra to r’s second argument is used to delimit output values. os tr ea m_ it er at or 3.8.4 Traversals and Predicates [tour2.traverse] Iterators allow us to write loops to iterate through a sequence. However, writing loops can be tedious, so the standard library provides ways for a function to be called for each element of a sequence. Consider writing a program that reads words from input and records the frequency of their occurrence. The obvious representation of the strings and their associated frequencies is a m ap ma p: m ap st ri ng in t> h is to gr am ma p<s tr in g,i nt hi st og ra m; The obvious action to be taken for each string to record its frequency is:
    72. 62 A Tour of the Standard Library Chapter 3 v oi d r ec or d(c on st s tr in g& s vo id re co rd co ns t st ri ng s) { h is to gr am s]++; hi st og ra m[s // record frequency of ‘‘s’’ } Once the input has been read, we would like to output the data we have gathered. The m ap consists ma p of a sequence of (string,int) pairs. Consequently, we would like to call v oi d p ri nt co ns t p ai r<c on st s tr in g,i nt r vo id pr in t(c on st pa ir co ns t st ri ng in t>& r) { c ou t << r fi rs t << ´ ´ << r se co nd << ´\\ n´; co ut r.f ir st r.s ec on d \\n } for each element in the map (the first element of a p ai r is called f ir st and the second element is pa ir fi rs t, called s ec on d). The first element of the p ai r is a c on st s tr in g rather than a plain s tr in g because all se co nd pa ir co ns t st ri ng st ri ng m ap keys are constants. ma p Thus, the main program becomes: i nt m ai n() in t ma in { i st re am _i te ra to r<s tr in g> i i(c in ; is tr ea m_ it er at or st ri ng ii ci n) i st re am _i te ra to r<s tr in g> e os is tr ea m_ it er at or st ri ng eo s; f or _e ac h(i i,e os re co rd ; fo r_ ea ch ii eo s,r ec or d) f or _e ac h(h is to gr am be gi n(),h is to gr am en d(),p ri nt ; fo r_ ea ch hi st og ra m.b eg in hi st og ra m.e nd pr in t) } Note that we don’t need to sort the m ap to get the output in order. A m ap keeps its elements ma p ma p ordered so that an iteration traverses the m ap in (increasing) order. ma p Many programming tasks involve looking for something in a container rather than simply doing something to every element. For example, the f in d algorithm (§18.5.2) provides a convenient way fi nd of looking for a specific value. A more general variant of this idea looks for an element that fulfills a specific requirement. For example, we might want to search a m ap for the first value larger than ma p 4 2. A m ap is a sequence of (key,value) pairs, so we search that list for a p ai r<c on st s tr in g,i nt 42 ma p pa ir co ns t st ri ng in t> where the i nt is greater than 4 2: in t 42 bo ol gt _4 2(c on st pa ir co ns t st ri ng in t>& r b oo l g t_ 42 co ns t p ai r<c on st s tr in g,i nt r) { r et ur n r se co nd 42 re tu rn r.s ec on d>4 2; } v oi d f ma p<s tr in g,i nt vo id f(m ap st ri ng in t>& m m) { t yp ed ef m ap st ri ng in t>::c on st _i te ra to r M I; ty pe de f ma p<s tr in g,i nt co ns t_ it er at or MI fi nd _i f(m be gi n() m.e nd gt _4 2) M I i = f in d_ if m.b eg in ,m en d(),g t_ 42 ; MI // ... } Alternatively, we could count the number of words with a frequency higher than 42:
    73. Section 3.8.4 Traversals and Predicates 63 v oi d g co ns t m ap st ri ng in t>& m vo id g(c on st ma p<s tr in g,i nt m) { i nt c 42 = c ou nt _i f(m be gi n(),m en d(),g t_ 42 ; gt _4 2) in t c4 2 co un t_ if m.b eg in m.e nd // ... } gt _4 2(), that is used to control the algorithm is called a predicate. A predicate A function, such as g t_ 42 is called for each element and returns a Boolean value, which the algorithm uses to perform its fi nd _i f() searches until its predicate returns t ru e to indicate that an intended action. For example, f in d_ if tr ue element of interest has been found. Similarly, c ou nt _i f() counts the number of times its predicate co un t_ if is t ru e. tr ue The standard library provides a few useful predicates and some templates that are useful for cre- ating more (§18.4.2). 3.8.5 Algorithms Using Member Functions [tour2.memp] Many algorithms apply a function to elements of a sequence. For example, in §3.8.4 f or _e ac h(i i,e os re co rd ; fo r_ ea ch ii eo s,r ec or d) calls r ec or d() to read strings from input. re co rd Often, we deal with containers of pointers and we really would like to call a member function of the object pointed to, rather than a global function on the pointer. For example, we might want to call the member function S ha pe :d ra w() for each element of a l is t<S ha pe Sh ap e: dr aw li st Sh ap e*>. To handle this specific example, we simply write a nonmember function that invokes the member function. For example: v oi d d ra w(S ha pe p vo id dr aw Sh ap e* p) { p dr aw ; p->d ra w() } v oi d f li st Sh ap e*>& s h) vo id f(l is t<S ha pe sh { f or _e ac h(s h.b eg in ,s h.e nd ,d ra w); fo r_ ea ch sh be gi n() sh en d() dr aw } By generalizing this technique, we can write the example like this: v oi d g li st Sh ap e*>& s h) vo id g(l is t<S ha pe sh { f or _e ac h(s h.b eg in ,s h.e nd ,m em _f un Sh ap e::d ra w)); fo r_ ea ch sh be gi n() sh en d() me m_ fu n(&S ha pe dr aw } The standard library m em _f un template (§18.4.4.2) takes a pointer to a member function (§15.5) me m_ fu n() as its argument and produces something that can be called for a pointer to the member’s class. The result of m em _f un Sh ap e::d ra w) takes a S ha pe me m_ fu n(&S ha pe dr aw Sh ap e* argument and returns whatever S ha pe :d ra w() returns. Sh ap e: dr aw The m em _f un me m_ fu n() mechanism is important because it allows the standard algorithms to be used for containers of polymorphic objects.
    74. 64 A Tour of the Standard Library Chapter 3 3.8.6 Standard Library Algorithms [tour2.algolist] What is an algorithm? A general definition of an algorithm is ‘‘a finite set of rules which gives a sequence of operations for solving a specific set of problems [and] has five important features: Finiteness ... Definiteness ... Input ... Output ... Effectiveness’’ [Knuth,1968,§1.1]. In the context of the C++ standard library, an algorithm is a set of templates operating on sequences of elements. The standard library provides dozens of algorithms. The algorithms are defined in namespace s td and presented in the <a lg or it hm header. Here are a few I have found particularly useful: st d al go ri th m> _ _____________________________________________________________________  _____________________________________________________________________ _ _ _____________________________________________________________________ Selected Standard Algorithms  f or _e ac h( ) fo r_ ea ch () Invoke function for each element (§18.5.1)    f in d( )  fi nd () Find first occurrence of arguments (§18.5.2)  f in d_ if () fi nd _i f( )  Find first match of predicate (§18.5.2)  c ou nt ()  co un t( ) Count occurrences of element (§18.5.3)  c ou nt _i f( )  co un t_ if () Count matches of predicate (§18.5.3)    r ep la ce () re pl ac e( ) Replace element with new value (§18.6.4)   r ep la ce _i f( ) Replace element that matches predicate with new value (§18.6.4)  re pl ac e_ if ()  c op y( )  co py () Copy elements (§18.6.1)  u ni qu e_ co py ()  un iq ue _c op y( ) Copy elements that are not duplicates (§18.6.1)  s or t( )  so rt () Sort elements (§18.7.1)    e qu al _r an ge () eq ua l_ ra ng e( ) Find all elements with equivalent values (§18.7.2)   me rg e( ) _m er ge () _____________________________________________________________________ Merge sorted sequences (§18.7.3) These algorithms, and many more (see Chapter 18), can be applied to elements of containers, s tr in gs, and built-in arrays. st ri ng 3.9 Math [tour2.math] Like C, C++ wasn’t designed primarily with numerical computation in mind. However, a lot of numerical work is done in C++, and the standard library reflects that. 3.9.1 Complex Numbers [tour2.complex] The standard library supports a family of complex number types along the lines of the c om pl ex co mp le x class described in §2.5.2. To support complex numbers where the scalars are single-precision, floating-point numbers (f lo at double precision numbers (d ou bl es), etc., the standard library c om - fl oa ts), do ub le co m- p le x is a template: pl ex t em pl at e<c la ss s ca la r> c la ss c om pl ex { te mp la te cl as s sc al ar cl as s co mp le x p ub li c: pu bl ic c om pl ex sc al ar r e, s ca la r i m); co mp le x(s ca la r re sc al ar im // ... }; The usual arithmetic operations and the most common mathematical functions are supported for complex numbers. For example:
    75. Section 3.9.1 Complex Numbers 65 // standard exponentiation function from <complex>: t em pl at e<c la ss C c om pl ex C> p ow co ns t c om pl ex C>&, i nt ; te mp la te cl as s C> co mp le x<C po w(c on st co mp le x<C in t) v oi d f co mp le x<f lo at f l, c om pl ex do ub le d b) vo id f(c om pl ex fl oa t> fl co mp le x<d ou bl e> db { c om pl ex lo ng d ou bl e> l d = f l+s qr t(d b); co mp le x<l on g do ub le ld fl sq rt db d b += f l*3 db fl 3; f l = p ow 1/f l,2 ; fl po w(1 fl 2) // ... } For more details, see §22.5. 3.9.2 Vector Arithmetic [tour2.valarray] The v ec to r described in §3.7.1 was designed to be a general mechanism for holding values, to be ve ct or flexible, and to fit into the architecture of containers, iterators, and algorithms. However, it does not support mathematical vector operations. Adding such operations to v ec to r would be easy, but ve ct or its generality and flexibility precludes optimizations that are often considered essential for serious numerical work. Consequently, the standard library provides a vector, called v al ar ra y, that is less va la rr ay general and more amenable to optimization for numerical computation: t em pl at e<c la ss T c la ss v al ar ra y { te mp la te cl as s T> cl as s va la rr ay // ... si ze _t T o pe ra to r[](s iz e_ t); T& op er at or // ... }; si ze _t The type s iz e_ t is the unsigned integer type that the implementation uses for array indices. The usual arithmetic operations and the most common mathematical functions are supported for v al ar ra ys. For example: va la rr ay // standard absolute value function from <valarray>: t em pl at e<c la ss T v al ar ra y<T a bs co ns t v al ar ra y<T te mp la te cl as s T> va la rr ay T> ab s(c on st va la rr ay T>&); v oi d f va la rr ay do ub le a 1, v al ar ra y<d ou bl e>& a 2) vo id f(v al ar ra y<d ou bl e>& a1 va la rr ay do ub le a2 { v al ar ra y<d ou bl e> a = a 1*3 14 a2 a1 va la rr ay do ub le a1 3.1 4+a 2/a 1; a 2 += a 1*3 14 a2 a1 3.1 4; a = a bs a); ab s(a d ou bl e d = a 2[7 ; do ub le a2 7] // ... } For more details, see §22.4. 3.9.3 Basic Numeric Support [tour2.basicnum] Naturally, the standard library contains the most common mathematical functions – such as l oglo g(), p ow po w(), and c os co s() – for floating-point types; see §22.3. In addition, classes that describe the properties of built-in types – such as the maximum exponent of a f lo at – are provided; see §22.2. fl oa t
    76. 66 A Tour of the Standard Library Chapter 3 3.10 Standard Library Facilities [tour2.post] The facilities provided by the standard library can be classified like this: [1] Basic run-time language support (e.g., for allocation and run-time type information); see §16.1.3. [2] The C standard library (with very minor modifications to minimize violations of the type system); see §16.1.2. [3] Strings and I/O streams (with support for international character sets and localization); see Chapter 20 and Chapter 21. [4] A framework of containers (such as v ec to r, l is t, and m ap and algorithms using containers ve ct or li st ma p) (such as general traversals, sorts, and merges); see Chapter 16, Chapter 17, Chapter 18, and Chapter 19. [5] Support for numerical computation (complex numbers plus vectors with arithmetic opera- tions, BLAS-like and generalized slices, and semantics designed to ease optimization); see Chapter 22. The main criterion for including a class in the library was that it would somehow be used by almost every C++ programmer (both novices and experts), that it could be provided in a general form that did not add significant overhead compared to a simpler version of the same facility, and that simple uses should be easy to learn. Essentially, the C++ standard library provides the most common fun- damental data structures together with the fundamental algorithms used on them. Every algorithm works with every container without the use of conversions. This framework, conventionally called the STL [Stepanov,1994], is extensible in the sense that users can easily pro- vide containers and algorithms in addition to the ones provided as part of the standard and have these work directly with the standard containers and algorithms. 3.11 Advice [tour2.advice] [1] Don’t reinvent the wheel; use libraries. [2] Don’t believe in magic; understand what your libraries do, how they do it, and at what cost they do it. [3] When you have a choice, prefer the standard library to other libraries. [4] Do not think that the standard library is ideal for everything. [5] Remember to #i nc lu de the headers for the facilities you use; §3.3. in cl ud e [6] Remember that standard library facilities are defined in namespace s td §3.3. st d; [7] Use s tr in g rather than c ha r*; §3.5, §3.6. st ri ng ch ar [8] If in doubt use a range-checked vector (such as V ec §3.7.2. Ve c); [9] Prefer v ec to r<T l is t<T and m ap ke y,v al ue to T ve ct or T>, li st T>, ma p<k ey va lu e> T[]; §3.7.1, §3.7.3, §3.7.4. pu sh _b ac k() ba ck _i ns er te r(); §3.7.3, §3.8. [10] When adding elements to a container, use p us h_ ba ck or b ac k_ in se rt er pu sh _b ac k() [11] Use p us h_ ba ck on a v ec to r rather than r ea ll oc on an array; §3.8. ve ct or re al lo c() [12] Catch common exceptions in m ai n(); §3.7.2. ma in
    77. Part I Basic Facilities This part describes C++’s built-in types and the basic facilities for constructing pro- grams out of them. The C subset of C++ is presented together with C++’s additional support for traditional styles of programming. It also discusses the basic facilities for composing a C++ program out of logical and physical parts. Chapters 4 Types and Declarations 5 Pointers, Arrays, and Structures 6 Expressions and Statements 7 Functions 8 Namespaces and Exceptions 9 Source Files and Programs
    78. 68 Basic Facilities Part I
    79. ________________________________________ ________________________________________________________________________________________________________________________________________________________________ 4 ________________________________________ ________________________________________________________________________________________________________________________________________________________________ Types and Declarations Accept nothing short of perfection! – anon Perfection is achieved only on the point of collapse. – C. N. Parkinson Types — fundamental types — Booleans — characters — character literals — integers — integer literals — floating-point types — floating-point literals — sizes — v oi d — vo id enumerations — declarations — names — scope — initialization — objects — t yp ed ef ty pe de fs — advice — exercises. 4.1 Types [dcl.type] Consider x = y f(2 ; y+f 2) For this to make sense in a C++ program, the names x y and f must be suitably declared. That is, x, y, the programmer must specify that entities named x y and f exist and that they are of types for x, y, which = (assignment), + (addition), and () (function call), respectively, are meaningful. Every name (identifier) in a C++ program has a type associated with it. This type determines what operations can be applied to the name (that is, to the entity referred to by the name) and how such operations are interpreted. For example, the declarations f lo at x fl oa t x; // x is a floating-point variable i nt y = 7 in t 7; // y is an integer variable with the initial value 7 f lo at f in t); fl oa t f(i nt // f is a function taking an argument of type int and returning a floating-point number
    80. 70 Types and Declarations Chapter 4 would make the example meaningful. Because y is declared to be an i nt it can be assigned to, used in t, in arithmetic expressions, etc. On the other hand, f is declared to be a function that takes an i nt as in t its argument, so it can be called given a suitable argument. This chapter presents fundamental types (§4.1.1) and declarations (§4.9). Its examples just demonstrate language features; they are not intended to do anything useful. More extensive and realistic examples are saved for later chapters after more of C++ has been described. This chapter simply provides the most basic elements from which C++ programs are constructed. You must know these elements, plus the terminology and simple syntax that goes with them, in order to com- plete a real project in C++ and especially to read code written by others. However, a thorough understanding of every detail mentioned in this chapter is not a requirement for understanding the following chapters. Consequently, you may prefer to skim through this chapter, observing the major concepts, and return later as the need for understanding of more details arises. 4.1.1 Fundamental Types [dcl.fundamental] C++ has a set of fundamental types corresponding to the most common basic storage units of a computer and the most common ways of using them to hold data: §4.2 A Boolean type (b oo l) bo ol §4.3 Character types (such as c ha r) ch ar §4.4 Integer types (such as i nt in t) §4.5 Floating-point types (such as d ou bl e) do ub le In addition, a user can define §4.8 Enumeration types for representing specific sets of values (e nu m) en um There also is §4.7 A type, v oi d, used to signify the absence of information vo id From these types, we can construct other types: §5.1 Pointer types (such as i nt in t*) §5.2 Array types (such as c ha r[]) ch ar §5.5 Reference types (such as d ou bl e&) do ub le §5.7 Data structures and classes (Chapter 10) The Boolean, character, and integer types are collectively called integral types. The integral and floating-point types are collectively called arithmetic types. Enumerations and classes (Chapter 10) are called user-defined types because they must be defined by users rather than being available for use without previous declaration, the way fundamental types are. In contrast, other types are called built-in types. The integral and floating-point types are provided in a variety of sizes to give the programmer a choice of the amount of storage consumed, the precision, and the range available for computations (§4.6). The assumption is that a computer provides bytes for holding characters, words for holding and computing integer values, some entity most suitable for floating-point computation, and addresses for referring to those entities. The C++ fundamental types together with pointers and arrays present these machine-level notions to the programmer in a reasonably implementation- independent manner. For most applications, one could simply use b oo l for logical values, c ha r for characters, i nt for bo ol ch ar in t integer values, and d ou bl e for floating-point values. The remaining fundamental types are do ub le
    81. Section 4.1.1 Fundamental Types 71 variations for optimizations and special needs that are best ignored until such needs arise. They must be known, however, to read old C and C++ code. 4.2 Booleans [dcl.bool] A Boolean, b oo l, can have one of the two values t ru e or f al se A Boolean is used to express the bo ol tr ue fa ls e. results of logical operations. For example: v oi d f in t a i nt b vo id f(i nt a, in t b) { b oo l b 1 = a b; bo ol b1 a==b // = is assignment, == is equality // ... } If a and b have the same value, b 1 becomes t ru e; otherwise, b 1 becomes f al se b1 tr ue b1 fa ls e. A common use of b oo l is as the type of the result of a function that tests some condition (a bo ol predicate). For example: bo ol is _o pe n(F il e*) b oo l i s_ op en Fi le ; b oo l g re at er in t a i nt b { r et ur n a b; } bo ol gr ea te r(i nt a, in t b) re tu rn a>b By definition, t ru e has the value 1 when converted to an integer and f al se has the value 0 Con- tr ue fa ls e 0. versely, integers can be implicitly converted to b oo l values: nonzero integers convert to t ru e and 0 bo ol tr ue converts to f al se For example: fa ls e. b oo l b = 7 bo ol 7; // bool(7) is true, so b becomes true i nt i = t ru e; in t tr ue // int(true) is 1, so i becomes 1 In arithmetic and logical expressions, b oo ls are converted to i nt integer arithmetic and logical bo ol in ts; operations are performed on the converted values. If the result is converted back to b oo l, a 0 is bo ol converted to f al se and a nonzero value is converted to t ru e. fa ls e tr ue v oi d g vo id g() { b oo l a = t ru e; bo ol tr ue b oo l b = t ru e; bo ol tr ue b oo l x = a b; // a+b is 2, so x becomes true bo ol a+b b oo l y = a b; // ab is 1, so y becomes true bo ol a|b } A pointer can be implicitly converted to a b oo l (§C.6.2.5). A nonzero pointer converts to t ru e; bo ol tr ue zero-valued pointers convert to f al se fa ls e. 4.3 Character Types [dcl.char] A variable of type c ha r can hold a character of the implementation’s character set. For example: ch ar c ha r c h = ´a ch ar ch a´;
    82. 72 Types and Declarations Chapter 4 Almost universally, a c ha r has 8 bits so that it can hold one of 256 different values. Typically, the ch ar character set is a variant of ISO-646, for example ASCII, thus providing the characters appearing on your keyboard. Many problems arise from the fact that this set of characters is only partially standardized (§C.3). Serious variations occur between character sets supporting different natural languages and also between different character sets supporting the same natural language in different ways. However, here we are interested only in how such differences affect the rules of C++. The larger and more interesting issue of how to program in a multi-lingual, multi-character-set environment is beyond the scope of this book, although it is alluded to in several places (§20.2, §21.7, §C.3.3). It is safe to assume that the implementation character set includes the decimal digits, the 26 alphabetic characters of English, and some of the basic punctuation characters. It is not safe to assume that there are no more than 127 characters in an 8-bit character set (e.g., some sets provide 255 characters), that there are no more alphabetic characters than English provides (most European languages provide more), that the alphabetic characters are contiguous (EBCDIC leaves a gap j´), or that every character used to write C++ is available (e.g., some national between ´i and ´j i´ character sets do not provide { } [ ] | \\ §C.3.1). Whenever possible, we should avoid making \\; assumptions about the representation of objects. This general rule applies even to characters. Each character constant has an integer value. For example, the value of ´b is 9 8 in the ASCII b´ 98 character set. Here is a small program that will tell you the integer value of any character you care to input: #i nc lu de <i os tr ea m> in cl ud e io st re am i nt m ai n() in t ma in { c ha r c ch ar c; s td :c in >> c st d: ci n c; s td :c ou t << \"t he v al ue o f ´\" << c << \"´ i s \" << i nt c) << ´\\ n´; st d: co ut th e va lu e of is in t(c \\n } The notation i nt c) gives the integer value for a character c The possibility of converting a c ha r in t(c c. ch ar to an integer raises the question: is a c ha r signed or unsigned? The 256 values represented by an ch ar 8-bit byte can be interpreted as the values 0 to 2 55 or as the values -1 27 to 1 27 Unfortunately, 25 5 12 7 12 7. which choice is made for a plain c ha r is implementation-defined (§C.1, §C.3.4). C++ provides two ch ar types for which the answer is definite; s ig ne d c ha r, which can hold at least the values -1 27 to 1 27 si gn ed ch ar 12 7 12 7, and u ns ig ne d c ha r, which can hold at least the values 0 to 2 55 Fortunately, the difference matters un si gn ed ch ar 25 5. only for values outside the 0 to 1 27 range, and the most common characters are within that range. 12 7 Values outside that range stored in a plain c ha r can lead to subtle portability problems. See ch ar §C.3.4 if you need to use more than one type of c ha r or if you store integers in c ha r variables. ch ar ch ar A type w ch ar _t is provided to hold characters of a larger character set such as Unicode. It is a wc ha r_ t distinct type. The size of w ch ar _t is implementation-defined and large enough to hold the largest wc ha r_ t character set supported by the implementation’s locale (see §21.7, §C.3.3). The strange name is a leftover from C. In C, w ch ar _t is a t yp ed ef (§4.9.7) rather than a built-in type. The suffix _ t was _t wc ha r_ t ty pe de f added to distinguish standard t yp ed ef ty pe de fs. Note that the character types are integral types (§4.1.1) so that arithmetic and logical operations (§6.2) apply.
    83. Section 4.3.1 Character Literals 73 4.3.1 Character Literals [dcl.char.lit] A character literal, often called a character constant, is a character enclosed in single quotes, for example, ´a and ´0 The type of a character literal is c ha r. Such character literals are really a´ 0´. ch ar symbolic constants for the integer value of the characters in the character set of the machine on which the C++ program is to run. For example, if you are running on a machine using the ASCII character set, the value of ´0 is 4 8. The use of character literals rather than decimal notation 0´ 48 makes programs more portable. A few characters also have standard names that use the backslash \\ as an escape character. For example, \\ n is a newline and \\ t is a horizontal tab. See §C.3.2 for \\n \\t details about escape characters. Wide character literals are of the form L ab where the number of characters between the L´a b´, quotes and their meanings is implementation-defined to match the w ch ar _t type. A wide character wc ha r_ t literal has type w ch ar _t wc ha r_ t. 4.4 Integer Types [dcl.int] Like c ha r, each integer type comes in three forms: ‘‘plain’’ i nt s ig ne d i nt and u ns ig ne d i nt In ch ar in t, si gn ed in t, un si gn ed in t. addition, integers come in three sizes: s ho rt i nt ‘‘plain’’ i nt and l on g i nt A l on g i nt can be sh or t in t, in t, lo ng in t. lo ng in t referred to as plain l on g. Similarly, s ho rt is a synonym for s ho rt i nt u ns ig ne d for u ns ig ne d i nt lo ng sh or t sh or t in t, un si gn ed un si gn ed in t, and s ig ne d for s ig ne d i nt si gn ed si gn ed in t. The u ns ig ne d integer types are ideal for uses that treat storage as a bit array. Using an un si gn ed u ns ig ne d instead of an i nt to gain one more bit to represent positive integers is almost never a good un si gn ed in t idea. Attempts to ensure that some values are positive by declaring variables u ns ig ne d will typi- un si gn ed cally be defeated by the implicit conversion rules (§C.6.1, §C.6.2.1). Unlike plain c ha rs, plain i nt are always signed. The signed i nt types are simply more explicit ch ar in ts in t synonyms for their plain i nt counterparts. in t 4.4.1 Integer Literals [dcl.int.lit] Integer literals come in four guises: decimal, octal, hexadecimal, and character literals. Decimal lit- erals are the most commonly used and look as you would expect them to: 0 1 23 4 12 34 9 76 97 6 1 23 45 67 89 01 23 45 67 89 0 12 34 56 78 90 12 34 56 78 90 The compiler ought to warn about literals that are too long to represent. A literal starting with zero followed by x (0 x) is a hexadecimal (base 16) number. A literal 0x starting with zero followed by a digit is an octal (base 8) number. For example: d ec im al de ci ma l: 0 2 63 63 83 83 o ct al oc ta l: 00 00 02 02 0 77 07 7 0 12 3 01 23 h ex ad ec im al he xa de ci ma l: 0 x0 0x 0 0 x2 0x 2 0 x3 f 0x 3f 0 x5 3 0x 53 The letters a b c d e and f or their uppercase equivalents, are used to represent 1 0, 1 1, 1 2, 1 3, a, b, c, d, e, f, 10 11 12 13 1 4, and 1 5, respectively. Octal and hexadecimal notations are most useful for expressing bit pat- 14 15 terns. Using these notations to express genuine numbers can lead to surprises. For example, on a machine on which an i nt is represented as a two’s complement 16-bit integer, 0 xf ff f is the negative in t 0x ff ff decimal number -1 Had more bits been used to represent an integer, it would have been 6 55 35 1. 65 53 5.
    84. 74 Types and Declarations Chapter 4 The suffix U can be used to write explicitly u ns ig ne d literals. Similarly, the suffix L can be un si gn ed used to write explicitly l on g literals. For example, 3 is an i nt 3U is an u ns ig ne d i nt and 3 L is a lo ng in t, un si gn ed in t, 3L l on g i nt If no suffix is provided, the compiler gives an integer literal a suitable type based on its lo ng in t. value and the implementation’s integer sizes (§C.4). It is a good idea to limit the use of nonobvious constants to a few well-commented c on st (§5.4) co ns t or enumerator (§4.8) initializers. 4.5 Floating-Point Types [dcl.float] The floating-point types represent floating-point numbers. Like integers, floating-point types come in three sizes: f lo at (single-precision), d ou bl e (double-precision), and l on g d ou bl e (extended- fl oa t do ub le lo ng do ub le precision). The exact meaning of single-, double-, and extended-precision is implementation-defined. Choosing the right precision for a problem where the choice matters requires significant under- standing of floating-point computation. If you don’t have that understanding, get advice, take the time to learn, or use d ou bl e and hope for the best. do ub le 4.5.1 Floating-Point Literals [dcl.fp.lit] By default, a floating-point literal is of type d ou bl e. Again, a compiler ought to warn about do ub le floating-point literals that are too large to be represented. Here are some floating-point literals: 1 23 1.2 3 .2 3 23 0 23 0.2 3 1 1. 10 1.0 1 2e 10 1.2 e1 0 1 23 e-1 5 1.2 3e 15 Note that a space cannot occur in the middle of a floating-point literal. For example, 6 5.4 3 e 21 65 43 e-2 1 is not a floating-point literal but rather four separate lexical tokens (causing a syntax error): 6 5.4 3 65 43 e 21 21 - If you want a floating-point literal of type f lo at you can define one using the suffix f or F fl oa t, F: 3 14 15 92 65 f 3.1 41 59 26 5f 2 0f 2.0 f 2 99 79 25 F 2.9 97 92 5F 4.6 Sizes [dcl.size] Some of the aspects of C++’s fundamental types, such as the size of an i nt are implementation- in t, defined (§C.2). I point out these dependencies and often recommend avoiding them or taking steps to minimize their impact. Why should you bother? People who program on a variety of systems or use a variety of compilers care a lot because if they don’t, they are forced to waste time finding and fixing obscure bugs. People who claim they don’t care about portability usually do so because they use only a single system and feel they can afford the attitude that ‘‘the language is what my com- piler implements.’’ This is a narrow and shortsighted view. If your program is a success, it is likely to be ported, so someone will have to find and fix problems related to implementation- dependent features. In addition, programs often need to be compiled with other compilers for the same system, and even a future release of your favorite compiler may do some things differently from the current one. It is far easier to know and limit the impact of implementation dependencies
    85. Section 4.6 Sizes 75 when a program is written than to try to untangle the mess afterwards. It is relatively easy to limit the impact of implementation-dependent language features. Limit- ing the impact of system-dependent library facilities is far harder. Using standard library facilities wherever feasible is one approach. The reason for providing more than one integer type, more than one unsigned type, and more than one floating-point type is to allow the programmer to take advantage of hardware characteris- tics. On many machines, there are significant differences in memory requirements, memory access times, and computation speed between the different varieties of fundamental types. If you know a machine, it is usually easy to choose, for example, the appropriate integer type for a particular vari- able. Writing truly portable low-level code is harder. Sizes of C++ objects are expressed in terms of multiples of the size of a c ha r, so by definition ch ar the size of a c ha r is 1 The size of an object or type can be obtained using the s iz eo f operator ch ar 1. si ze of (§6.2). This is what is guaranteed about sizes of fundamental types: 1 ≡ sizeof(char) ≤ sizeof(short) ≤ sizeof(int) ≤ sizeof(long) 1 ≤ sizeof(bool) ≤ sizeof(long) sizeof(char) ≤ sizeof(wchar_t) ≤ sizeof(long) sizeof(float) ≤ sizeof(double) ≤ sizeof(long double) sizeof(N) ≡ sizeof(signed N) ≡ sizeof(unsigned N) where N can be c ha r, s ho rt i nt i nt or l on g i nt In addition, it is guaranteed that a c ha r has at least ch ar sh or t in t, in t, lo ng in t. ch ar 8 bits, a s ho rt at least 16 bits, and a l on g at least 32 bits. A c ha r can hold a character of the sh or t lo ng ch ar machine’s character set. Here is a graphical representation of a plausible set of fundamental types and a sample string: char: ’a’ bool: 1 short: 756 int: 100000000 int*: &c1 double: 1234567e34 char[14]: Hello, world!\\0 On the same scale (.2 inch to a byte), a megabyte of memory would stretch about three miles (five km) to the right.
    86. 76 Types and Declarations Chapter 4 The c ha r type is supposed to be chosen by the implementation to be the most suitable type for ch ar holding and manipulating characters on a given computer; it is typically an 8-bit byte. Similarly, the i nt type is supposed to be chosen to be the most suitable for holding and manipulating integers in t on a given computer; it is typically a 4-byte (32-bit) word. It is unwise to assume more. For exam- ple, there are machines with 32 bit c ha rs. ch ar When needed, implementation-dependent aspects about an implementation can be found in <l im it s> (§22.2). For example: li mi ts #i nc lu de <l im it s> in cl ud e li mi ts i nt m ai n() in t ma in { c ou t << \"l ar ge st f lo at == \" << n um er ic _l im it s<f lo at :m ax co ut la rg es t fl oa t nu me ri c_ li mi ts fl oa t>: ma x() << \", c ha r i s s ig ne d == \" << n um er ic _l im it s<c ha r>::i s_ si gn ed << ´\\ n´; is _s ig ne d ch ar is si gn ed nu me ri c_ li mi ts ch ar \\n } The fundamental types can be mixed freely in assignments and expressions. Wherever possible, values are converted so as not to lose information (§C.6). If a value v can be represented exactly in a variable of type T a conversion of v to T is value- T, preserving and no problem. The cases where conversions are not value-preserving are best avoided (§C.6.2.6). You need to understand implicit conversion in some detail in order to complete a major project and especially to understand real code written by others. However, such understanding is not required to read the following chapters. 4.7 Void [dcl.void] The type v oi d is syntactically a fundamental type. It can, however, be used only as part of a more vo id complicated type; there are no objects of type v oi d. It is used either to specify that a function does vo id not return a value or as the base type for pointers to objects of unknown type. For example: v oi d x vo id x; // error: there are no void objects v oi d f ; vo id f() // function f does not return a value (§7.3) v oi d* p v; vo id pv // pointer to object of unknown type (§5.6) When declaring a function, you must specify the type of the value returned. Logically, you would expect to be able to indicate that a function didn’t return a value by omitting the return type. How- ever, that would make the grammar (Appendix A) less regular and clash with C usage. Conse- quently, v oi d is used as a ‘‘pseudo return type’’ to indicate that a function doesn’t return a value. vo id 4.8 Enumerations [dcl.enum] An enumeration is a type that can hold a set of values specified by the user. Once defined, an enu- meration is used very much like an integer type. Named integer constants can be defined as members of an enumeration. For example, e nu m { A SM A UT O, B RE AK }; en um AS M, AU TO BR EA K
    87. Section 4.8 Enumerations 77 defines three integer constants, called enumerators, and assigns values to them. By default, enu- merator values are assigned increasing from 0 so A SM 0, A UT O==1 and B RE AK 2. An enu- 0, AS M==0 AU TO 1, BR EA K==2 meration can be named. For example: e nu m k ey wo rd { A SM A UT O, B RE AK }; en um ke yw or d AS M, AU TO BR EA K Each enumeration is a distinct type. The type of an enumerator is its enumeration. For example, A UT O is of type k ey wo rd AU TO ke yw or d. Declaring a variable k ey wo rd instead of plain i nt can give both the user and the compiler a hint ke yw or d in t as to the intended use. For example: v oi d f ke yw or d k ey vo id f(k ey wo rd ke y) { s wi tc h (k ey { sw it ch ke y) c as e A SM ca se AS M: // do something b re ak br ea k; c as e B RE AK ca se BR EA K: // do something b re ak br ea k; } } A compiler can issue a warning because only two out of three k ey wo rd values are handled. ke yw or d An enumerator can be initialized by a constant-expression (§C.5) of integral type (§4.1.1). The range of an enumeration holds all the enumeration’s enumerator values rounded up to the nearest larger binary power minus 1 The range goes down to 0 if the smallest enumerator is non-negative 1. and to the nearest lesser negative binary power if the smallest enumerator is negative. This defines the smallest bit-field capable of holding the enumerator values. For example: e nu m e 1 { d ar k, l ig ht }; en um e1 da rk li gh t // range 0:1 e nu m e 2 { a = 3 b = 9 }; en um e2 3, // range 0:15 e nu m e 3 { m in = -1 0, m ax = 1 00 00 00 }; // range -1048576:1048575 en um e3 mi n 10 ma x 10 00 00 0 A value of integral type may be explicitly converted to an enumeration type. The result of such a conversion is undefined unless the value is within the range of the enumeration. For example: e nu m f la g { x 1, y 2, z 4, e 8 }; // range 0:15 en um fl ag x=1 y=2 z=4 e=8 f la g f 1 = 5 fl ag f1 5; // type error: 5 is not of type flag f la g f 2 = f la g(5 ; fl ag f2 fl ag 5) // ok: flag(5) is of type flag and within the range of flag f la g f 3 = f la g(z e); // ok: flag(12) is of type flag and within the range of flag fl ag f3 fl ag z|e f la g f 4 = f la g(9 9); // undefined: 99 is not within the range of flag fl ag f4 fl ag 99 The last assignment shows why there is no implicit conversion from an integer to an enumeration; most integer values do not have a representation in a particular enumeration. The notion of a range of values for an enumeration differs from the enumeration notion in the Pascal family of languages. However, bit-manipulation examples that require values outside the set of enumerators to be well-defined have a long history in C and C++.
    88. 78 Types and Declarations Chapter 4 The s iz eo f an enumeration is the s iz eo f some integral type that can hold its range and not larger si ze of si ze of than s iz eo f(i nt unless an enumerator cannot be represented as an i nt or as an u ns ig ne d i nt For si ze of in t), in t un si gn ed in t. example, s iz eo f(e 1) could be 1 or maybe 4 but not 8 on a machine where s iz eo f(i nt si ze of e1 si ze of in t)==4 4. By default, enumerations are converted to integers for arithmetic operations (§6.2). An enumer- ation is a user-defined type, so users can define their own operations, such as ++ and << for an enu- meration (§11.2.3). 4.9 Declarations [dcl.dcl] Before a name (identifier) can be used in a C++ program, it must be declared. That is, its type must be specified to inform the compiler to what kind of entity the name refers. Here are some examples illustrating the diversity of declarations: c ha r c h; ch ar ch s tr in g s st ri ng s; i nt c ou nt = 1 in t co un t 1; c on st d ou bl e p i = 3 14 15 92 65 35 89 79 32 38 5; co ns t do ub le pi 3.1 41 59 26 53 58 97 93 23 85 e xt er n i nt e rr or _n um be r; ex te rn in t er ro r_ nu mb er c ha r* n am e = \"N ja l\"; ch ar na me Nj al c ha r* s ea so n[] = { \"s pr in g\", \"s um me r\", \"f al l\", \"w in te r\" }; ch ar se as on sp ri ng su mm er fa ll wi nt er s tr uc t D at e { i nt d m y }; st ru ct Da te in t d, m, y; i nt d ay Da te p { r et ur n p d; } in t da y(D at e* p) re tu rn p->d d ou bl e s qr t(d ou bl e); do ub le sq rt do ub le t em pl at e<c la ss T T a bs T a { r et ur n a 0 ? -a : a } te mp la te cl as s T> ab s(T a) re tu rn a<0 a a; t yp ed ef c om pl ex sh or t> P oi nt ty pe de f co mp le x<s ho rt Po in t; s tr uc t U se r; st ru ct Us er e nu m B ee r { C ar ls be rg T ub or g, T ho r }; en um Be er Ca rl sb er g, Tu bo rg Th or n am es pa ce N S { i nt a } na me sp ac e NS in t a; As can be seen from these examples, a declaration can do more than simply associate a type with a name. Most of these declarations are also definitions; that is, they also define an entity for the name to which they refer. For c h, that entity is the appropriate amount of memory to be used as a ch variable – that memory will be allocated. For d ay it is the specified function. For the constant p i, da y, pi it is the value 3 14 15 92 65 35 89 79 32 38 5. For D at e, that entity is a new type. For P oi nt it is the 3.1 41 59 26 53 58 97 93 23 85 Da te Po in t, type c om pl ex sh or t> so that P oi nt becomes a synonym for c om pl ex sh or t>. Of the declarations co mp le x<s ho rt Po in t co mp le x<s ho rt above, only d ou bl e s qr t(d ou bl e); do ub le sq rt do ub le e xt er n i nt e rr or _n um be r; ex te rn in t er ro r_ nu mb er s tr uc t U se r; st ru ct Us er are not also definitions; that is, the entity they refer to must be defined elsewhere. The code (body) for the function s qr t must be specified by some other declaration, the memory for the i nt variable sq rt in t e rr or _n um be r must be allocated by some other declaration of e rr or _n um be r, and some other er ro r_ nu mb er er ro r_ nu mb er declaration of the type U se r must define what that type looks like. For example: Us er
    89. Section 4.9 Declarations 79 d ou bl e s qr t(d ou bl e d { /* ... */ } do ub le sq rt do ub le d) i nt e rr or _n um be r = 1 in t er ro r_ nu mb er 1; s tr uc t U se r { /* ... */ }; st ru ct Us er There must always be exactly one definition for each name in a C++ program (for the effects of #i nc lu de see §9.2.3). However, there can be many declarations. All declarations of an entity must in cl ud e, agree on the type of the entity referred to. So, this fragment has two errors: i nt c ou nt in t co un t; i nt c ou nt // error: redefinition in t co un t; e xt er n i nt e rr or _n um be r; ex te rn in t er ro r_ nu mb er e xt er n s ho rt e rr or _n um be r; ex te rn sh or t er ro r_ nu mb er // error: type mismatch and this has none (for the use of e xt er n see §9.2): ex te rn e xt er n i nt e rr or _n um be r; ex te rn in t er ro r_ nu mb er e xt er n i nt e rr or _n um be r; ex te rn in t er ro r_ nu mb er Some definitions specify a ‘‘value’’ for the entities they define. For example: s tr uc t D at e { i nt d m y }; st ru ct Da te in t d, m, y; t yp ed ef c om pl ex sh or t> P oi nt ty pe de f co mp le x<s ho rt Po in t; i nt d ay Da te p { r et ur n p d; } in t da y(D at e* p) re tu rn p->d c on st d ou bl e p i = 3 14 15 92 65 35 89 79 32 38 5; co ns t do ub le pi 3.1 41 59 26 53 58 97 93 23 85 For types, templates, functions, and constants, the ‘‘value’’ is permanent. For nonconstant data types, the initial value may be changed later. For example: v oi d f vo id f() { i nt c ou nt = 1 in t co un t 1; c ha r* n am e = \"B ja rn e\"; ch ar na me Bj ar ne // ... c ou nt = 2 co un t 2; n am e = \"M ar ia n\"; na me Ma ri an } Of the definitions, only c ha r c h; ch ar ch s tr in g s st ri ng s; do not specify values. See §4.9.5 and §10.4.2 for explanations of how and when a variable is assigned a default value. Any declaration that specifies a value is a definition. 4.9.1 The Structure of a Declaration [dcl.parts] A declaration consists of four parts: an optional ‘‘specifier,’’ a base type, a declarator, and an optional initializer. Except for function and namespace definitions, a declaration is terminated by a semicolon. For example:
    90. 80 Types and Declarations Chapter 4 c ha r* k in gs = { \"A nt ig on us \"S el eu cu s\", \"P to le my }; ch ar ki ng s[] An ti go nu s\", Se le uc us Pt ol em y\" Here, the base type is c ha r, the declarator is *k in gs ch ar ki ng s[], and the initializer is ={...}. A specifier is an initial keyword, such as v ir tu al (§2.5.5, §12.2.6) and e xt er n (§9.2), that speci- vi rt ua l ex te rn fies some non-type attribute of what is being declared. A declarator is composed of a name and optionally some declarator operators. The most com- mon declarator operators are (§A.7.1): p oi nt er po in te r p re fi x pr ef ix * *c on st co ns t c on st an t p oi nt er co ns ta nt po in te r p re fi x pr ef ix r ef er en ce re fe re nc e p re fi x pr ef ix & a rr ay ar ra y p os tf ix po st fi x [] f un ct io n fu nc ti on p os tf ix po st fi x () Their use would be simple if they were all either prefix or postfix. However, *, [], and () were designed to mirror their use in expressions (§6.2). Thus, * is prefix and [] and () are postfix. The postfix declarator operators bind tighter than the prefix ones. Consequently, *k in gs ki ng s[] is a vector of pointers to something, and we have to use parentheses to express types such as ‘‘pointer to function;’’ see examples in §5.1. For full details, see the grammar in Appendix A. Note that the type cannot be left out of a declaration. For example: c on st c = 7 co ns t 7; // error: no type g t(i nt a i nt b { r et ur n (a b) ? a : b } // error: no return type gt in t a, in t b) re tu rn a>b b; u ns ig ne d u i; un si gn ed ui // ok: ‘unsigned’ is the type ‘unsigned int’ l on g l i; lo ng li // ok: ‘long’ is the type ‘long int’ In this, standard C++ differs from earlier versions of C and C++ that allowed the first two examples by considering i nt to be the type when none were specified (§B.2). This ‘‘implicit i nt rule was a in t in t’’ source of subtle errors and confusion. 4.9.2 Declaring Multiple Names [dcl.multi] It is possible to declare several names in a single declaration. The declaration simply contains a list of comma-separated declarators. For example, we can declare two integers like this: i nt x y in t x, y; // int x; int y; Note that operators apply to individual names only – and not to any subsequent names in the same declaration. For example: i nt p y in t* p, y; // int* p; int y; NOT int* y; i nt x *q in t x, q; // int x; int* q; i nt v 10 , *p v; in t v[1 0] pv // int v[10]; int* pv; Such constructs make a program less readable and should be avoided.
    91. Section 4.9.3 Names 81 4.9.3 Names [dcl.name] A name (identifier) consists of a sequence of letters and digits. The first character must be a letter. The underscore character _ is considered a letter. C++ imposes no limit on the number of charac- ters in a name. However, some parts of an implementation are not under the control of the com- piler writer (in particular, the linker), and those parts, unfortunately, sometimes do impose limits. Some run-time environments also make it necessary to extend or restrict the set of characters accepted in an identifier. Extensions (e.g., allowing the character $ in a name) yield nonportable programs. A C++ keyword (Appendix A), such as n ew and i nt cannot be used as a name of a ne w in t, user-defined entity. Examples of names are: t hi s_ is _a _m os t_ un us ua ll y_ lo ng _n am e th is _i s_ a_ mo st _u nu su al ly _l on g_ na me h el lo he ll o u _n am e D EF IN ED DE FI NE D f oO fo O b Ar bA r u_ na me H or se Se ns e Ho rs eS en se _ cl as s _c la ss _ __ __ _ v ar 0 va r0 v ar 1 va r1 C LA SS CL AS S Examples of character sequences that cannot be used as identifiers are: 0 12 01 2 a f oo l fo ol $s ys sy s c la ss cl as s 3 va r 3v ar p ay du e pa y.d ue f oo ba r fo o~b ar .n am e na me if if Names starting with an underscore are reserved for special facilities in the implementation and the run-time environment, so such names should not be used in application programs. When reading a program, the compiler always looks for the longest string of characters that could make up a name. Hence, v ar 10 is a single name, not the name v ar followed by the number va r1 0 va r 1 0. Also, e ls ei f is a single name, not the keyword e ls e followed by the keyword i f. 10 el se if el se if Uppercase and lowercase letters are distinct, so C ou nt and c ou nt are different names, but it is Co un t co un t unwise to choose names that differ only by capitalization. In general, it is best to avoid names that differ only in subtle ways. For example, the uppercase o (O and zero (0 can be hard to tell apart, O) 0) as can the lowercase L (l and one (1 Consequently, l 0, l O, l 1, and l l are poor choices for identi- l) 1). l0 lO l1 ll fier names. Names from a large scope ought to have relatively long and reasonably obvious names, such as v ec to r, W in do w_ wi th _b or de r, and D ep ar tm en t_ nu mb er However, code is clearer if names used ve ct or Wi nd ow _w it h_ bo rd er De pa rt me nt _n um be r. only in a small scope have short, conventional names such as x i and p Classes (Chapter 10) and x, i, p. namespaces (§8.2) can be used to keep scopes small. It is often useful to keep frequently used names relatively short and reserve really long names for infrequently used entities. Choose names to reflect the meaning of an entity rather than its implementation. For example, p ho ne _b oo k is bet- ph on e_ bo ok nu mb er _l is t ter than n um be r_ li st even if the phone numbers happen to be stored in a l is t (§3.7). Choosing good li st names is an art. Try to maintain a consistent naming style. For example, capitalize nonstandard library user- defined types and start nontypes with a lowercase letter (for example, S ha pe and c ur re nt _t ok en Sh ap e cu rr en t_ to ke n). Also, use all capitals for macros (if you must use macros; for example, H AC K) and use underscores HA CK to separate words in an identifier. However, consistency is hard to achieve because programs are typically composed of fragments from different sources and several different reasonable styles are in use. Be consistent in your use of abbreviations and acronyms.
    92. 82 Types and Declarations Chapter 4 4.9.4 Scope [dcl.scope] A declaration introduces a name into a scope; that is, a name can be used only in a specific part of the program text. For a name declared in a function (often called a local name), that scope extends from its point of declaration to the end of the block in which its declaration occurs. A block is a section of code delimited by a { } pair. A name is called global if it is defined outside any function, class (Chapter 10), or namespace (§8.2). The scope of a global name extends from the point of declaration to the end of the file in which its declaration occurs. A declaration of a name in a block can hide a declaration in an enclosing block or a global name. That is, a name can be redefined to refer to a different entity within a block. After exit from the block, the name resumes its previous meaning. For example: i nt x in t x; // global x v oi d f vo id f() { i nt x in t x; // local x hides global x x=1 1; // assign to local x { i nt x in t x; // hides first local x x=2 2; // assign to second local x } x=3 3; // assign to first local x } i nt p = &x in t* x; // take address of global x Hiding names is unavoidable when writing large programs. However, a human reader can easily fail to notice that a name has been hidden. Because such errors are relatively rare, they can be very difficult to find. Consequently, name hiding should be minimized. Using names such as i and x for global variables or for local variables in a large function is asking for trouble. A hidden global name can be referred to using the scope resolution operator ::. For example: i nt x in t x; v oi d f 2() vo id f2 { i nt x = 1 // hide global x in t 1; ::x = 2 x 2; // assign to global x x=2 2; // assign to local x // ... } There is no way to use a hidden local name. The scope of a name starts at its point of declaration; that is, after the complete declarator and before the initializer. This implies that a name can be used even to specify its own initial value. For example: i nt x in t x;
    93. Section 4.9.4 Scope 83 v oi d f 3() vo id f3 { i nt x = x // perverse: initialize x with its own (uninitialized) value in t x; } This is not illegal, just silly. A good compiler will warn if a variable is used before it has been set (see also §5.9[9]). It is possible to use a single name to refer to two different objects in a block without using the :: operator. For example: i nt x = 1 1; in t 11 v oi d f 4() vo id f4 // perverse: { i nt y = x in t x; // use global x: y = 11 i nt x = 2 2; in t 22 y=x x; // use local x: y = 22 } Function argument names are considered declared in the outermost block of a function, so v oi d f 5(i nt x vo id f5 in t x) { i nt x in t x; // error } is an error because x is defined twice in the same scope. Having this be an error allows a not uncommon, subtle mistake to be caught. 4.9.5 Initialization [dcl.init] If an initializer is specified for an object, that initializer determines the initial value of an object. If no initializer is specified, a global (§4.9.4), namespace (§8.2), or local static object (§7.1.2, §10.2.4) (collectively called static objects) is initialized to 0 of the appropriate type. For example: i nt a in t a; // means ‘‘int a = 0;’’ d ou bl e d do ub le d; // means ‘‘double d = 0.0;’’ Local variables (sometimes called automatic objects) and objects created on the free store (some- times called dynamic objects or heap objects) are not initialized by default. For example: v oi d f vo id f() { i nt x in t x; // x does not have a well-defined value // ... } Members of arrays and structures are default initialized or not depending on whether the array or structure is static. User-defined types may have default initialization defined (§10.4.2). More complicated objects require more than one value as an initializer. This is handled by ini- tializer lists delimited by { and } for C-style initialization of arrays (§5.2.1) and structures (§5.7). For user-defined types with constructors, function-style argument lists are used (§2.5.2, §10.2.3).
    94. 84 Types and Declarations Chapter 4 Note that an empty pair of parentheses () in a declaration always means ‘‘function’’ (§7.1). For example: i nt a in t a[] = { 1 2 }; 1, // array initializer P oi nt z 1,2 ; Po in t z(1 2) // function-style initializer (initialization by constructor) i nt f ; in t f() // function declaration 4.9.6 Objects and Lvalues [dcl.objects] We can allocate and use ‘‘variables’’ that do not have names, and it is possible to assign to strange-looking expressions (e.g., *p a+1 0]=7 Consequently, there is a need for a name for p[a 10 7). ‘‘something in memory.’’ This is the simplest and most fundamental notion of an object. That is, an object is a contiguous region of storage; an lvalue is an expression that refers to an object. The word lvalue was originally coined to mean ‘‘something that can be on the left-hand side of an assignment.’’ However, not every lvalue may be used on the left-hand side of an assignment; an lvalue can refer to a constant (§5.5). An lvalue that has not been declared c on st is often called a co ns t modifiable lvalue. This simple and low-level notion of an object should not be confused with the notions of class object and object of polymorphic type (§15.4.3). Unless the programmer specifies otherwise (§7.1.2, §10.4.8), an object declared in a function is created when its definition is encountered and destroyed when its name goes out of scope (§10.4.4). Such objects are called automatic objects. Objects declared in global or namespace scope and s ta t-st at - i cs declared in functions or classes are created and initialized once (only) and ‘‘live’’ until the pro- ic gram terminates (§10.4.9). Such objects are called static objects. Array elements and nonstatic structure or class members have their lifetimes determined by the object of which they are part. Using the n ew and d el et e operators, you can create objects whose lifetimes are controlled ne w de le te directly (§6.2.6). 4.9.7 Typedef [dcl.typedef] A declaration prefixed by the keyword t yp ed ef declares a new name for the type rather than a new ty pe de f variable of the given type. For example: t yp ed ef c ha r* P ch ar ty pe de f ch ar Pc ha r; P ch ar p 1, p 2; Pc ha r p1 p2 // p1 and p2 are char*s c ha r* p 3 = p 1; ch ar p3 p1 A name defined like this, usually called a ‘‘ t yp ed ef can be a convenient shorthand for a type ty pe de f,’’ with an unwieldy name. For example, u ns ig ne d c ha r is too long for really frequent use, so we un si gn ed ch ar could define a synonym, u ch ar uc ha r: t yp ed ef u ns ig ne d c ha r u ch ar ty pe de f un si gn ed ch ar uc ha r; Another use of a t yp ed ef is to limit the direct reference to a type to one place. For example: ty pe de f t yp ed ef i nt i nt 32 ty pe de f in t in t3 2; t yp ed ef s ho rt i nt 16 ty pe de f sh or t in t1 6; If we now use i nt 32 wherever we need a potentially large integer, we can port our program to a in t3 2 machine on which s iz eo f(i nt is 2 by redefining the single occurrence of i nt in our code: si ze of in t) in t
    95. Section 4.9.7 Typedef 85 t yp ed ef l on g i nt 32 ty pe de f lo ng in t3 2; For good and bad, t yp ed ef are synonyms for other types rather than distinct types. Consequently, ty pe de fs t yp ed ef mix freely with the types for which they are synonyms. People who would like to have ty pe de fs distinct types with identical semantics or identical representation should look at enumerations (§4.8) or classes (Chapter 10). 4.10 Advice [dcl.advice] [1] Keep scopes small; §4.9.4. [2] Don’t use the same name in both a scope and an enclosing scope; §4.9.4. [3] Declare one name (only) per declaration; §4.9.2. [4] Keep common and local names short, and keep uncommon and nonlocal names longer; §4.9.3. [5] Avoid similar-looking names; §4.9.3. [6] Maintain a consistent naming style; §4.9.3. [7] Choose names carefully to reflect meaning rather than implementation; §4.9.3. [8] Use a t yp ed ef to define a meaningful name for a built-in type in cases in which the built-in ty pe de f type used to represent a value might change; §4.9.7. [9] Use t yp ed ef to define synonyms for types; use enumerations and classes to define new types; ty pe de fs §4.9.7. [10] Remember that every declaration must specify a type (there is no ‘‘implicit i nt in t’’); §4.9.1. [11] Avoid unnecessary assumptions about the numeric value of characters; §4.3.1, §C.6.2.1. [12] Avoid unnecessary assumptions about the size of integers; §4.6. [13] Avoid unnecessary assumptions about the range of floating-point types; §4.6. [14] Prefer a plain i nt over a s ho rt i nt or a l on g i nt §4.6. in t sh or t in t lo ng in t; [15] Prefer a d ou bl e over a f lo at or a l on g d ou bl e; §4.5. do ub le fl oa t lo ng do ub le [16] Prefer plain c ha r over s ig ne d c ha r and u ns ig ne d c ha r; §C.3.4. ch ar si gn ed ch ar un si gn ed ch ar [17] Avoid making unnecessary assumptions about the sizes of objects; §4.6. [18] Avoid unsigned arithmetic; §4.4. [19] View s ig ne d to u ns ig ne d and u ns ig ne d to s ig ne d conversions with suspicion; §C.6.2.6. si gn ed un si gn ed un si gn ed si gn ed [20] View floating-point to integer conversions with suspicion; §C.6.2.6. [21] View conversions to a smaller type, such as i nt to c ha r, with suspicion; §C.6.2.6. in t ch ar 4.11 Exercises [dcl.exercises] 1. (∗2) Get the ‘‘Hello, world!’’ program (§3.2) to run. If that program doesn’t compile as writ- ten, look at §B.3.1. 2. (∗1) For each declaration in §4.9, do the following: If the declaration is not a definition, write a definition for it. If the declaration is a definition, write a declaration for it that is not also a defi- nition. 3. (∗1.5) Write a program that prints the sizes of the fundamental types, a few pointer types, and a few enumerations of your choice. Use the s iz eo f operator. si ze of
    96. 86 Types and Declarations Chapter 4 4. (∗1.5) Write a program that prints out the letters ´a a´..´z and the digits ´0 z´ 0´..´9 and their 9´ integer values. Do the same for other printable characters. Do the same again but use hexa- decimal notation. 5. (∗2) What, on your system, are the largest and the smallest values of the following types: c ha r, ch ar s ho rt i nt l on g, f lo at d ou bl e, l on g d ou bl e, and u ns ig ne d. sh or t, in t, lo ng fl oa t, do ub le lo ng do ub le un si gn ed 6. (∗1) What is the longest local name you can use in a C++ program on your system? What is the longest external name you can use in a C++ program on your system? Are there any restrictions on the characters you can use in a name? 7. (∗2) Draw a graph of the integer and fundamental types where a type points to another type if all values of the first can be represented as values of the second on every standards-conforming implementation. Draw the same graph for the types on your favorite implementation.
    97. ________________________________________ ________________________________________________________________________________________________________________________________________________________________ 5 ________________________________________ ________________________________________________________________________________________________________________________________________________________________ Pointers, Arrays, and Structures The sublime and the ridiculous are often so nearly related that it is difficult to class them separately. – Tom Paine Pointers — zero — arrays — string literals — pointers into arrays — constants — point- ers and constants — references — v oi d* — data structures — advice — exercises. vo id 5.1 Pointers [ptr.ptr] For a type T T is the type ‘‘pointer to T That is, a variable of type T can hold the address of T, T* T.’’ T* an object of type T For example: T. c ha r c = ´a ch ar a´; c ha r* p = &c ch ar c; // p holds the address of c or graphically: p p: c &c .. c ’a c: a’ Unfortunately, pointers to arrays and pointers to functions need a more complicated notation: i nt p i; in t* pi // pointer to int c ha r** p pc ch ar pp c; // pointer to pointer to char i nt a p[1 5]; in t* ap 15 // array of 15 pointers to ints i nt (*f p)(c ha r*); in t fp ch ar // pointer to function taking a char* argument; returns an int i nt f ch ar ; in t* f(c ha r*) // function taking a char* argument; returns a pointer to int See §4.9.1 for an explanation of the declaration syntax and Appendix A for the complete grammar.
    98. 88 Pointers, Arrays, and Structures Chapter 5 The fundamental operation on a pointer is dereferencing, that is, referring to the object pointed to by the pointer. This operation is also called indirection. The dereferencing operator is (prefix) unary *. For example: c ha r c = ´a ch ar a´; c ha r* p = &c ch ar c; // p holds the address of c c ha r c 2 = *p // c2 == ’a’ ch ar c2 p; The variable pointed to by p is c and the value stored in c is ´a so the value of *p assigned to c 2 c, a´, p c2 is ´a a´. It is possible to perform some arithmetic operations on pointers to array elements (§5.3). Point- ers to functions can be extremely useful; they are discussed in §7.7. The implementation of pointers is intended to map directly to the addressing mechanisms of the machine on which the program runs. Most machines can address a byte. Those that can’t tend to have hardware to extract bytes from words. On the other hand, few machines can directly address an individual bit. Consequently, the smallest object that can be independently allocated and pointed to using a built-in pointer type is a c ha r. Note that a b oo l occupies at least as much space ch ar bo ol as a c ha r (§4.6). To store smaller values more compactly, you can use logical operations (§6.2.4) ch ar or bit fields in structures (§C.8.1). 5.1.1 Zero [ptr.zero] Zero (0 is an i nt Because of standard conversions (§C.6.2.3), 0 can be used as a constant of any 0) in t. integral (§4.1.1), floating-point, pointer, or pointer-to-member type. The type of zero will be deter- mined by context. Zero will typically (but not necessarily) be represented by the bit pattern all- zeros of the appropriate size. No object is allocated with the address 0 Consequently, 0 acts as a pointer literal, indicating 0. that a pointer doesn’t refer to an object. In C, it has been popular to define a macro N UL L to represent the zero pointer. Because of NU LL C++’s tighter type checking, the use of plain 0 rather than any suggested N UL L macro, leads to 0, NU LL fewer problems. If you feel you must define N UL L, use NU LL c on st i nt N UL L = 0 co ns t in t NU LL 0; The c on st qualifier (§5.4) prevents accidental redefinition of N UL L and ensures that N UL L can be co ns t NU LL NU LL used where a constant is required. 5.2 Arrays [ptr.array] For a type T T si ze is the type ‘‘array of s iz e elements of type T T, T[s iz e] si ze T.’’ The elements are indexed from 0 to s iz e-1 For example: si ze 1. f lo at v 3]; fl oa t v[3 // an array of three floats: v[0], v[1], v[2] c ha r* a 32 ; ch ar a[3 2] // an array of 32 pointers to char: a[0] .. a[31]
    99. Section 5.2 Arrays 89 The number of elements of the array, the array bound, must be a constant expression (§C.5). If you need variable bounds, use a v ec to r (§3.7.1, §16.3). For example: ve ct or v oi d f in t i vo id f(i nt i) { i nt v 1[i ; in t v1 i] // error: array size not a constant expression v ec to r<i nt v 2(i ; ve ct or in t> v2 i) // ok } Multidimensional arrays are represented as arrays of arrays. For example: i nt d 2[1 0][2 0]; // d2 is an array of 10 arrays of 20 integers in t d2 10 20 Using comma notation as used for array bounds in some other languages gives compile-time errors because comma (,) is a sequencing operator (§6.2.2) and is not allowed in constant expressions (§C.5). For example, try this: i nt b ad 5,2 ; in t ba d[5 2] // error: comma not allowed in a constant expression Multidimensional arrays are described in §C.7. They are best avoided outside low-level code. 5.2.1 Array Initializers [ptr.array.init] An array can be initialized by a list of values. For example: i nt v 1[] = { 1 2 3 4 }; in t v1 1, 2, 3, c ha r v 2[] = { ´a ch ar v2 a´, ´bb´, ´c c´, 0 }; When an array is declared without a specific size, but with an initializer list, the size is calculated by counting the elements of the initializer list. Consequently, v 1 and v 2 are of type i nt 4] and v1 v2 in t[4 c ha r[4 respectively. If a size is explicitly specified, it is an error to give surplus elements in an ch ar 4], initializer list. For example: c ha r v 3[2 = { ´a ch ar v3 2] a´, ´b b´, 0 }; // error: too many initializers c ha r v 4[3 = { ´a ch ar v4 3] a´, ´b b´, 0 }; // ok If the initializer supplies too few elements, 0 is assumed for the remaining array elements. For example: i nt v 5[8 = { 1 2 3 4 }; in t v5 8] 1, 2, 3, is equivalent to i nt v 5[] = { 1 2 3 4 , 0 0 0 0 }; in t v5 1, 2, 3, 0, 0, 0, Note that there is no array assignment to match the initialization: v oi d f vo id f() { v 4 = { ´c v4 c´, ´d d´, 0 }; // error: no array assignment } When you need such assignments, use a v ec to r (§16.3) or a v al ar ra y (§22.4) instead. ve ct or va la rr ay An array of characters can be conveniently initialized by a string literal (§5.2.2).
    100. 90 Pointers, Arrays, and Structures Chapter 5 5.2.2 String Literals [ptr.string.literal] A string literal is a character sequence enclosed within double quotes: \"t hi s i s a s tr in g\" th is is st ri ng A string literal contains one more character than it appears to have; it is terminated by the null char- acter ´\\ 0´, with the value 0 For example: \\0 0. s iz eo f(\"B oh r\")==5 si ze of Bo hr 5 The type of a string literal is ‘‘array of the appropriate number of c on st characters,’’ so \" Bo hr \" is co ns t \"B oh r\" of type c on st c ha r[5 co ns t ch ar 5]. A string literal can be assigned to a c ha r*. This is allowed because in previous definitions of C ch ar and C++ , the type of a string literal was c ha r*. Allowing the assignment of a string literal to a ch ar c ha r* ensures that millions of lines of C and C++ remain valid. It is, however, an error to try to ch ar modify a string literal through such a pointer: v oi d f vo id f() { c ha r* p = \"P la to ch ar Pl at o\"; p 4] = ´e p[4 e´; // error: assignment to const; result is undefined } This kind of error cannot in general be caught until run-time, and implementations differ in their enforcement of this rule. Having string literals constant not only is obvious, but also allows imple- mentations to do significant optimizations in the way string literals are stored and accessed. If we want a string that we are guaranteed to be able to modify, we must copy the characters into an array: v oi d f vo id f() { c ha r p ch ar p[] = \"Z en o\"; Ze no // p is an array of 5 char p 0] = ´R p[0 R´; // ok } A string literal is statically allocated so that it is safe to return one from a function. For example: c on st c ha r* e rr or _m es sa ge in t i co ns t ch ar er ro r_ me ss ag e(i nt i) { // ... r et ur n \"r an ge e rr or re tu rn ra ng e er ro r\"; } The memory holding r an ge e rr or will not go away after a call of e rr or _m es sa ge ra ng e er ro r er ro r_ me ss ag e(). Whether two identical character literals are allocated as one is implementation-defined (§C.1). For example: c on st c ha r* p = \"H er ac li tu s\"; co ns t ch ar He ra cl it us c on st c ha r* q = \"H er ac li tu s\"; co ns t ch ar He ra cl it us
    101. Section 5.2.2 String Literals 91 v oi d g vo id g() { i f (p == q c ou t << \"o ne \\n if p q) co ut on e!\\ n\"; // result is implementation-defined // ... } Note that == compares addresses (pointer values) when applied to pointers, and not the values pointed to. The empty string is written as a pair of adjacent double quotes, \"\", (and has the type c on st co ns t c ha r[1 ch ar 1]). The backslash convention for representing nongraphic characters (§C.3.2) can also be used within a string. This makes it possible to represent the double quote (\") and the escape character backslash ( \\ within a string. The most common such character by far is the newline character, \\) ´\\ n´. For example: \\n c ou t<<\"b ee p a t e nd o f m es sa ge \\a \\n co ut be ep at en d of me ss ag e\\ a\\ n\"; The escape character ´\\ a´ is the ASCII character B EL (also known as alert), which causes some \\a BE L kind of sound to be emitted. It is not possible to have a ‘‘real’’ newline in a string: \"t hi s i s n ot a s tr in g th is is no t st ri ng b ut a s yn ta x e rr or bu t sy nt ax er ro r\" Long strings can be broken by whitespace to make the program text neater. For example: c ha r a lp ha ch ar al ph a[] = \"a bc de fg hi jk lm no pq rs tu vw xy z\" ab cd ef gh ij kl mn op qr st uv wx yz \"A BC DE FG HI JK LM NO PQ RS TU VW XY Z\"; AB CD EF GH IJ KL MN OP QR ST UV WX YZ The compiler will concatenate adjacent strings, so a lp ha could equivalently have been initialized al ph a by the single string: \"a bc de fg hi jk lm no pq rs tu vw xy zA BC DE FG HI JK LM NO PQ RS TU VW XY Z\"; ab cd ef gh ij kl mn op qr st uv wx yz AB CD EF GH IJ KL MN OP QR ST UV WX YZ It is possible to have the null character in a string, but most programs will not suspect that there are characters after it. For example, the string \" Je ns \\0 00 Mu nk \" will be treated as \" Je ns \" by stan- \"J en s\\ 00 0M un k\" \"J en s\" dard library functions such as s tr cp y() and s tr le n(); see §20.4.1. st rc py st rl en A string with the prefix L such as L an gs t\", is a string of wide characters (§4.3, §C.3.3). Its L, L\"a ng st type is c on st w ch ar _t co ns t wc ha r_ t[]. 5.3 Pointers into Arrays [ptr.into] In C++, pointers and arrays are closely related. The name of an array can be used as a pointer to its initial element. For example: i nt v = { 1 2 3 4 }; in t v[] 1, 2, 3, i nt p 1 = v in t* p1 v; // pointer to initial element (implicit conversion) i nt p 2 = &v 0]; in t* p2 v[0 // pointer to initial element i nt p 3 = &v 4]; in t* p3 v[4 // pointer to one beyond last element or graphically:
    102. 92 Pointers, Arrays, and Structures Chapter 5 p1 p1 p2 p2 p3 p3 . .... v v: 1234 .. Taking a pointer to the element one beyond the end of an array is guaranteed to work. This is important for many algorithms (§2.7.2, §18.3). However, since such a pointer does not in fact point to an element of the array, it may not be used for reading or writing. The result of taking the address of the element before the initial element is undefined and should be avoided. On some machine architectures, arrays are often allocated on machine addressing boundaries, so ‘‘one before the initial element’’ simply doesn’t make sense. The implicit conversion of an array name to a pointer to the initial element of the array is exten- sively used in function calls in C-style code. For example: e xt er n \"C i nt s tr le n(c on st c ha r*); // from <string.h> ex te rn C\" in t st rl en co ns t ch ar v oi d f vo id f() { c ha r v = \"A nn em ar ie ch ar v[] An ne ma ri e\"; c ha r* p = v ch ar v; // implicit conversion of char[] to char* s tr le n(p ; st rl en p) s tr le n(v ; st rl en v) // implicit conversion of char[] to char* v=p p; // error: cannot assign to array } The same value is passed to the standard library function s tr le n() in both calls. The snag is that it st rl en is impossible to avoid the implicit conversion. In other words, there is no way of declaring a func- tion so that the array v is copied when the function is called. Fortunately, there is no implicit or explicit conversion from a pointer to an array. The implicit conversion of the array argument to a pointer means that the size of the array is lost to the called function. However, the called function must somehow determine the size to perform a meaningful operation. Like other C standard library functions taking pointers to characters, s tr le n() relies on zero to indicate end-of-string; s tr le n(p returns the number of characters up to st rl en st rl en p) and not including the terminating 0 This is all pretty low-level. The standard library v ec to r 0. ve ct or (§16.3) and s tr in g (Chapter 20) don’t suffer from this problem. st ri ng 5.3.1 Navigating Arrays [ptr.navigate] Efficient and elegant access to arrays (and similar data structures) is the key to many algorithms (see §3.8, Chapter 18). Access can be achieved either through a pointer to an array plus an index or through a pointer to an element. For example, traversing a character string using an index, v oi d f i(c ha r v vo id fi ch ar v[]) { f or (i nt i = 0 v i]!=0 i fo r in t 0; v[i 0; i++) u se v[i ; us e(v i]) }
    103. Section 5.3.1 Navigating Arrays 93 is equivalent to a traversal using a pointer: v oi d f p(c ha r v vo id fp ch ar v[]) { f or (c ha r* p = v *p 0; p fo r ch ar v; p!=0 p++) u se p); us e(*p } The prefix * operator dereferences a pointer so that *p is the character pointed to by p p p,and ++ increments the pointer so that it refers to the next element of the array. There is no inherent reason why one version should be faster than the other. With modern com- pilers, identical code should be generated for both examples (see §5.9[8]). Programmers can choose between the versions on logical and aesthetic grounds. The result of applying the arithmetic operators +, -, ++, or -- to pointers depends on the type of the object pointed to. When an arithmetic operator is applied to a pointer p of type T p is T*, assumed to point to an element of an array of objects of type T p 1 points to the next element of T; p+1 that array, and p 1 points to the previous element. This implies that the integer value of p 1 will p-1 p+1 be s iz eo f(T larger than the integer value of p For example, executing si ze of T) p. #i nc lu de <i os tr ea m> in cl ud e io st re am i nt m ai n () in t ma in { i nt v i[1 0]; in t vi 10 s ho rt v s[1 0]; sh or t vs 10 s td :c ou t << &v i[0 << ´ ´ << &v i[1 << ´\\ n´; st d: co ut vi 0] vi 1] \\n s td :c ou t << &v s[0 << ´ ´ << &v s[1 << ´\\ n´; st d: co ut vs 0] vs 1] \\n } produced 0 x7 ff fa ef 0 0 x7 ff fa ef 4 0x 7f ff ae f0 0x 7f ff ae f4 0 x7 ff fa ed c 0 x7 ff fa ed e 0x 7f ff ae dc 0x 7f ff ae de using a default hexadecimal notation for pointer values. This shows that on my implementation, s iz eo f(s ho rt is 2 and s iz eo f(i nt is 4 si ze of sh or t) si ze of in t) 4. Subtraction of pointers is defined only when both pointers point to elements of the same array (although the language has no fast way of ensuring that is the case). When subtracting one pointer from another, the result is the number of array elements between the two pointers (an integer). One can add an integer to a pointer or subtract an integer from a pointer; in both cases, the result is a pointer value. If that value does not point to an element of the same array as the original pointer or one beyond, the result of using that value is undefined. For example: v oi d f vo id f() { i nt v 1[1 0]; in t v1 10 i nt v 2[1 0]; in t v2 10 i nt i 1 = &v 1[5 in t i1 v1 5]-&v 1[3 ; // i1 = 2 v1 3] i nt i 2 = &v 1[5 in t i2 v1 5]-&v 2[3 ; // result undefined v2 3]
    104. 94 Pointers, Arrays, and Structures Chapter 5 i nt p 1 = v 2+2 in t* p1 v2 2; // p1 = &v2[2] i nt p 2 = v 2-2 in t* p2 v2 2; // *p2 undefined } Complicated pointer arithmetic is usually unnecessary and often best avoided. Addition of pointers makes no sense and is not allowed. Arrays are not self-describing because the number of elements of an array is not guaranteed to be stored with the array. This implies that to traverse an array that does not contain a terminator the way character strings do, we must somehow supply the number of elements. For example: v oi d f p(c ha r v , u ns ig ne d i nt s iz e) vo id fp ch ar v[] un si gn ed in t si ze { f or (i nt i 0; i si ze i fo r in t i=0 i<s iz e; i++) u se v[i ; us e(v i]) c on st i nt N = 7 co ns t in t 7; c ha r v 2[N ; ch ar v2 N] f or (i nt i 0; i N; i fo r in t i=0 i<N i++) u se v2 i]); us e(v 2[i } Note that most C++ implementations offer no range checking for arrays. This array concept is inherently low-level. A more advanced notion of arrays can be provided through the use of classes; see §3.7.1. 5.4 Constants [ptr.const] C++ offers the concept of a user-defined constant, a c on st to express the notion that a value doesn’t co ns t, change directly. This is useful in several contexts. For example, many objects don’t actually have their values changed after initialization, symbolic constants lead to more maintainable code than do literals embedded directly in code, pointers are often read through but never written through, and most function parameters are read but not written to. The keyword c on st can be added to the declaration of an object to make the object declared a co ns t constant. Because it cannot be assigned to, a constant must be initialized. For example: c on st i nt m od el = 9 0; co ns t in t mo de l 90 // model is a const c on st i nt v = { 1 2 3 4 }; co ns t in t v[] 1, 2, 3, // v[i] is a const c on st i nt x co ns t in t x; // error: no initializer Declaring something c on st ensures that its value will not change within its scope: co ns t v oi d f vo id f() { m od el = 2 00 mo de l 20 0; // error v 2]++; v[2 // error } Note that c on st modifies a type; that is, it restricts the ways in which an object can be used, rather co ns t than specifying how the constant is to be allocated. For example:
    105. Section 5.4 Constants 95 v oi d g co ns t X p vo id g(c on st X* p) { // can’t modify *p here } v oi d h vo id h() { X v al va l; // val can be modified g va l); g(&v al // ... } Depending on how smart it is, a compiler can take advantage of an object being a constant in sev- eral ways. For example, the initializer for a constant is often (but not always) a constant expression (§C.5); if it is, it can be evaluated at compile time. Further, if the compiler knows every use of the c on st it need not allocate space to hold it. For example: co ns t, c on st i nt c 1 = 1 co ns t in t c1 1; c on st i nt c 2 = 2 co ns t in t c2 2; co ns t in t c3 my _f 3) c on st i nt c 3 = m y_ f(3 ; // don’t know the value of c3 at compile time e xt er n c on st i nt c 4; ex te rn co ns t in t c4 // don’t know the value of c4 at compile time c on st i nt p = &c 2; co ns t in t* c2 // need to allocate space for c2 Given this, the compiler knows the values of c 1 and c 2 so that they can be used in constant expres- c1 c2 sions. Because the values of c 3 and c 4 are not known at compile time (using only the information c3 c4 available in this compilation unit; see §9.1), storage must be allocated for c 3 and c 4. Because the c3 c4 address of c 2 is taken (and presumably used somewhere), storage must be allocated for c 2. The c2 c2 simple and common case is the one in which the value of the constant is known at compile time and no storage needs to be allocated; c 1 is an example of that. The keyword e xt er n indicates that c 4 is c1 ex te rn c4 defined elsewhere (§9.2). It is typically necessary to allocate store for an array of constants because the compiler cannot, in general, figure out which elements of the array are referred to in expressions. On many machines, however, efficiency improvements can be achieved even in this case by placing arrays of constants in read-only storage. Common uses for c on st are as array bounds and case labels. For example: co ns ts c on st i nt a = 4 2; co ns t in t 42 c on st i nt b = 9 9; co ns t in t 99 c on st i nt m ax = 1 28 co ns t in t ma x 12 8; i nt v ma x]; in t v[m ax v oi d f in t i vo id f(i nt i) { s wi tc h (i { sw it ch i) c as e a ca se a: // ...
    106. 96 Pointers, Arrays, and Structures Chapter 5 c as e b ca se b: // ... } } Enumerators (§4.8) are often an alternative to c on st in such cases. co ns ts The way c on st can be used with class member functions is discussed in §10.2.6 and §10.2.7. co ns t Symbolic constants should be used systematically to avoid ‘‘magic numbers’’ in code. If a numeric constant, such as an array bound, is repeated in code, it becomes hard to revise that code because every occurrence of that constant must be changed to make a correct update. Using a sym- bolic constant instead localizes information. Usually, a numeric constant represents an assumption about the program. For example, 4 may represent the number of bytes in an integer, 1 28 the num- 12 8 ber of characters needed to buffer input, and 6 24 the exchange factor between Danish kroner and 6.2 4 U.S. dollars. Left as numeric constants in the code, these values are hard for a maintainer to spot and understand. Often, such numeric values go unnoticed and become errors when a program is ported or when some other change violates the assumptions they represent. Representing assump- tions as well-commented symbolic constants minimizes such maintenance problems. 5.4.1 Pointers and Constants [ptr.pc] When using a pointer, two objects are involved: the pointer itself and the object pointed to. ‘‘Pre- fixing’’ a declaration of a pointer with c on st makes the object, but not the pointer, a constant. To co ns t declare a pointer itself, rather than the object pointed to, to be a constant, we use the declarator operator *c on st instead of plain *. For example: co ns t v oi d f 1(c ha r* p vo id f1 ch ar p) { c ha r s ch ar s[] = \"G or m\"; Go rm c on st c ha r* p c = s co ns t ch ar pc s; // pointer to constant p c[3 = ´g pc 3] g´; // error: pc points to constant pc = p pc p; // ok c ha r *c on st c p = s ch ar co ns t cp s; // constant pointer c p[3 = ´a cp 3] a´; // ok cp = p cp p; // error: cp is constant c on st c ha r *c on st c pc = s co ns t ch ar co ns t cp c s; // const pointer to const c pc 3] = ´a cp c[3 a´; // error: cpc points to constant c pc = p cp c p; // error: cpc is constant } The declarator operator that makes a pointer constant is *c on st There is no c on st declarator co ns t. co ns t* operator, so a c on st appearing before the * is taken to be part of the base type. For example: co ns t c ha r *c on st c p; ch ar co ns t cp // const pointer to char c ha r c on st p c; ch ar co ns t* pc // pointer to const char c on st c ha r* p c2 co ns t ch ar pc 2; // pointer to const char Some people find it helpful to read such declarations right-to-left. For example, ‘‘c p is a c on st cp co ns t pointer to a c ha r’’ and ‘‘p c2 is a pointer to a c ha r c on st ch ar pc 2 ch ar co ns t.’’
    107. Section 5.4.1 Pointers and Constants 97 An object that is a constant when accessed through one pointer may be variable when accessed in other ways. This is particularly useful for function arguments. By declaring a pointer argument c on st the function is prohibited from modifying the object pointed to. For example: co ns t, c ha r* s tr cp y(c ha r* p c on st c ha r* q ; // cannot modify *q ch ar st rc py ch ar p, co ns t ch ar q) You can assign the address of a variable to a pointer to constant because no harm can come from that. However, the address of a constant cannot be assigned to an unrestricted pointer because this would allow the object’s value to be changed. For example: v oi d f 4() vo id f4 { i nt a = 1 in t 1; c on st i nt c = 2 co ns t in t 2; c on st i nt p 1 = &c co ns t in t* p1 c; // ok c on st i nt p 2 = &a co ns t in t* p2 a; // ok i nt p 3 = &c in t* p3 c; // error: initialization of int* with const int* *p 3 = 7 p3 7; // try to change the value of c } It is possible to explicitly remove the restrictions on a pointer to c on st by explicit type conversion co ns t (§10.2.7.1 and §15.4.2.1). 5.5 References [ptr.ref] A reference is an alternative name for an object. The main use of references is for specifying argu- ments and return values for functions in general and for overloaded operators (Chapter 11) in par- ticular. The notation X means reference to X For example: X& X. v oi d f vo id f() { i nt i = 1 in t 1; i nt r = i in t& i; // r and i now refer to the same int i nt x = r in t r; // x = 1 r=2 2; // i = 2 } To ensure that a reference is a name for something (that is, bound to an object), we must initialize the reference. For example: i nt i = 1 in t 1; i nt r 1 = i in t& r1 i; // ok: r1 initialized i nt r 2; in t& r2 // error: initializer missing e xt er n i nt r 3; ex te rn in t& r3 // ok: r3 initialized elsewhere Initialization of a reference is something quite different from assignment to it. Despite appear- ances, no operator operates on a reference. For example:
    108. 98 Pointers, Arrays, and Structures Chapter 5 v oi d g vo id g() { i nt i i = 0 in t ii 0; i nt r r = i i; in t& rr ii r r++; rr // ii is incremented to 1 i nt p p = &r r; in t* pp rr // pp points to ii } This is legal, but r r++ does not increment the reference r r; rather, ++ is applied to an i nt that hap- rr rr in t pens to be i i. Consequently, the value of a reference cannot be changed after initialization; it ii always refers to the object it was initialized to denote. To get a pointer to the object denoted by a reference r r, we can write &r r. rr rr The obvious implementation of a reference is as a (constant) pointer that is dereferenced each time it is used. It doesn’t do much harm thinking about references that way, as long as one remem- bers that a reference isn’t an object that can be manipulated the way a pointer is: p p: pp &i i ii r r: rr i i: ii 1 In some cases, the compiler can optimize away a reference so that there is no object representing that reference at run-time. Initialization of a reference is trivial when the initializer is an lvalue (an object whose address you can take; see §4.9.6). The initializer for a ‘‘plain’’ T must be an lvalue of type T T& T. The initializer for a c on st T need not be an lvalue or even of type T In such cases, co ns t T& T. [1] first, implicit type conversion to T is applied if necessary (see §C.6); [2] then, the resulting value is placed in a temporary variable of type T and T; [3] finally, this temporary variable is used as the value of the initializer. Consider: d ou bl e& d r = 1 do ub le dr 1; // error: lvalue needed c on st d ou bl e& c dr = 1 co ns t do ub le cd r 1; // ok The interpretation of this last initialization might be: d ou bl e t em p = d ou bl e(1 ; // first create a temporary with the right value do ub le te mp do ub le 1) c on st d ou bl e& c dr = t em p; // then use the temporary as the initializer for cdr co ns t do ub le cd r te mp A temporary created to hold a reference initializer persists until the end of its reference’s scope. References to variables and references to constants are distinguished because the introduction of a temporary in the case of the variable is highly error-prone; an assignment to the variable would become an assignment to the – soon to disappear – temporary. No such problem exists for refer- ences to constants, and references to constants are often important as function arguments (§11.6). A reference can be used to specify a function argument so that the function can change the value of an object passed to it. For example:
    109. Section 5.5 References 99 v oi d i nc re me nt in t& a a) { a a++; } vo id in cr em en t(i nt aa aa v oi d f vo id f() { i nt x = 1 in t 1; i nc re me nt x); in cr em en t(x // x = 2 } The semantics of argument passing are defined to be those of initialization, so when called, i nc re me nt argument a a became another name for x To keep a program readable, it is often best in cr em en t’s aa x. to avoid functions that modify their arguments. Instead, you can return a value from the function explicitly or require a pointer argument: i nt n ex t(i nt p { r et ur n p 1; } in t ne xt in t p) re tu rn p+1 v oi d i nc r(i nt p { (*p vo id in cr in t* p) p)++; } v oi d g vo id g() { i nt x = 1 in t 1; i nc re me nt x); in cr em en t(x // x = 2 x = n ex t(x ; ne xt x) // x = 3 i nc r(&x ; in cr x) // x = 4 } The i nc re me nt x) notation doesn’t give a clue to the reader that x value is being modified, the in cr em en t(x x’s way x ne xt x) and i nc r(&x does. Consequently ‘‘plain’’ reference arguments should be used x=n ex t(x in cr x) only where the name of the function gives a strong hint that the reference argument is modified. References can also be used to define functions that can be used on both the left-hand and right-hand sides of an assignment. Again, many of the most interesting uses of this are found in the design of nontrivial user-defined types. As an example, let us define a simple associative array. First, we define struct P ai r like this: Pa ir s tr uc t P ai r { st ru ct Pa ir s tr in g n am e; st ri ng na me d ou bl e v al do ub le va l; }; The basic idea is that a s tr in g has a floating-point value associated with it. It is easy to define a st ri ng function, v al ue va lu e(), that maintains a data structure consisting of one P ai r for each different string Pa ir that has been presented to it. To shorten the presentation, a very simple (and inefficient) implemen- tation is used: v ec to r<P ai r> p ai rs ve ct or Pa ir pa ir s; d ou bl e& v al ue co ns t s tr in g& s do ub le va lu e(c on st st ri ng s) /* maintain a set of Pairs: search for s, return its value if found; otherwise make a new Pair and return the default value 0 */ {
    110. 100 Pointers, Arrays, and Structures Chapter 5 f or (i nt i = 0 i < p ai rs si ze ; i fo r in t 0; pa ir s.s iz e() i++) i f (s == p ai rs i].n am e) r et ur n p ai rs i].v al if s pa ir s[i na me re tu rn pa ir s[i va l; P ai r p = { s 0 }; Pa ir s, p ai rs pu sh _b ac k(p ; // add Pair at end (§3.7.3) pa ir s.p us h_ ba ck p) r et ur n p ai rs pa ir s.s iz e()-1 va l; re tu rn pa ir s[p ai rs si ze 1].v al } This function can be understood as an array of floating-point values indexed by character strings. For a given argument string, v al ue va lu e() finds the corresponding floating-point object (not the value of the corresponding floating-point object); it then returns a reference to it. For example: i nt m ai n() // count the number of occurrences of each word on input in t ma in { s tr in g b uf st ri ng bu f; w hi le (c in bu f) v al ue bu f)++; wh il e ci n>>b uf va lu e(b uf f or (v ec to r<P ai r>::c on st _i te ra to r p = p ai rs be gi n(); p pa ir s.e nd ; ++p fo r ve ct or Pa ir co ns t_ it er at or pa ir s.b eg in p!=p ai rs en d() p) c ou t << p na me << \": \" << p va l << ´\\ n´; co ut p->n am e p->v al \\n } Each time around, the w hi le wh il e-loop reads one word from the standard input stream c in into the string ci n b uf (§3.6) and then updates the counter associated with it. Finally, the resulting table of different bu f words in the input, each with its number of occurrences, is printed. For example, given the input aa bb bb aa aa bb aa aa aa bb bb aa aa bb aa aa this program will produce: a a: 5 aa b b: 3 bb It is easy to refine this into a proper associative array type by using a template class with the selec- tion operator [] overloaded (§11.8). It is even easier just to use the standard library m ap (§17.4.1). ma p 5.6 Pointer to Void [ptr.ptrtovoid] A pointer of any type of object can be assigned to a variable of type v oi d*, a v oi d* can be assigned vo id vo id to another v oi d*, v oi d*s can be compared for equality and inequality, and a v oi d* can be explicitly vo id vo id vo id converted to another type. Other operations would be unsafe because the compiler cannot know what kind of object is really pointed to. Consequently, other operations result in compile-time errors. To use a v oi d*, we must explicitly convert it to a pointer to a specific type. For example: vo id v oi d f in t* p i) vo id f(i nt pi { v oi d* p v = p i; // ok: implicit conversion of int* to void* vo id pv pi *p v; pv // error: can’t dereference void* p v++; pv // error: can’t increment void* (the size of the object pointed to is unknown)
    111. Section 5.6 Pointer to Void 101 in t* pi 2 st at ic _c as t<i nt i nt p i2 = s ta ti c_ ca st in t*>(p v); pv // explicit conversion back to int* d ou bl e* p d1 = p v; do ub le pd 1 pv // error d ou bl e* p d2 = p i; do ub le pd 2 pi // error do ub le pd 3 st at ic _c as t<d ou bl e*>(p v); // unsafe d ou bl e* p d3 = s ta ti c_ ca st do ub le pv } In general, it is not safe to use a pointer that has been converted (‘‘cast’’) to a type that differs from the type the object pointed to. For example, a machine may assume that every d ou bl e is allocated do ub le on an 8-byte boundary. If so, strange behavior could arise if p i pointed to an i nt that wasn’t allo- pi in t cated that way. This form of explicit type conversion is inherently unsafe and ugly. Consequently, st at ic _c as t, the notation used, s ta ti c_ ca st was designed to be ugly. The primary use for v oi d* is for passing pointers to functions that are not allowed to make vo id assumptions about the type of the object and for returning untyped objects from functions. To use such an object, we must use explicit type conversion. Functions using v oi d* pointers typically exist at the very lowest level of the system, where real vo id hardware resources are manipulated. For example: vo id my _a ll oc si ze _t n) v oi d* m y_ al lo c(s iz e_ t n ; // allocate n bytes from my special heap Occurrences of v oi d*s at higher levels of the system should be viewed with suspicion because they vo id are likely indicators of design errors. Where used for optimization, v oi d* can be hidden behind a vo id type-safe interface (§13.5, §24.4.2). Pointers to functions (§7.7) and pointers to members (§15.5) cannot be assigned to v oi d*s. vo id 5.7 Structures [ptr.struct] An array is an aggregate of elements of the same type. A s tr uc t is an aggregate of elements of st ru ct (nearly) arbitrary types. For example: s tr uc t a dd re ss { st ru ct ad dr es s c ha r* n am e; ch ar na me // \"Jim Dandy\" l on g i nt n um be r; lo ng in t nu mb er // 61 c ha r* s tr ee t; ch ar st re et // \"South St\" c ha r* t ow n; ch ar to wn // \"New Providence\" c ha r s ta te 2]; ch ar st at e[2 // ’N’ ’J’ l on g z ip lo ng zi p; // 7974 }; This defines a new type called a dd re ss consisting of the items you need in order to send mail to ad dr es s someone. Note the semicolon at the end. This is one of very few places in C++ where it is neces- sary to have a semicolon after a curly brace, so people are prone to forget it. Variables of type a dd re ss can be declared exactly as other variables, and the individual ad dr es s members can be accessed using the . (dot) operator. For example:
    112. 102 Pointers, Arrays, and Structures Chapter 5 v oi d f vo id f() { a dd re ss j d; ad dr es s jd j d.n am e = \"J im D an dy jd na me Ji m Da nd y\"; j d.n um be r = 6 1; jd nu mb er 61 } The notation used for initializing arrays can also be used for initializing variables of structure types. For example: a dd re ss j d = { ad dr es s jd \"J im D an dy Ji m Da nd y\", 6 1, \"S ou th S t\", 61 So ut h St \"N ew P ro vi de nc e\", {´N Ne w Pr ov id en ce N´,´J J´}, 7 97 4 79 74 }; Using a constructor (§10.2.3) is usually better, however. Note that j d.s ta te could not be initialized jd st at e by the string \" NJ \". Strings are terminated by the character ´\\ 0´. Hence, \" NJ \" has three characters \"N J\" \\0 \"N J\" – one more than will fit into j d.s ta te jd st at e. Structure objects are often accessed through pointers using the -> (structure pointer derefer- ence) operator. For example: v oi d p ri nt _a dd r(a dd re ss p vo id pr in t_ ad dr ad dr es s* p) { c ou t << p na me << ´\\ n´ co ut p->n am e \\n << p nu mb er << ´ ´ << p st re et << ´\\ n´ p->n um be r p->s tr ee t \\n << p to wn << ´\\ n´ p->t ow n \\n << p st at e[0 << p st at e[1 << ´ ´ << p zi p << ´\\ n´; p->s ta te 0] p->s ta te 1] p->z ip \\n } When p is a pointer, p m is equivalent to (*p m. p->m p).m Objects of structure types can be assigned, passed as function arguments, and returned as the result from a function. For example: a dd re ss c ur re nt ad dr es s cu rr en t; a dd re ss s et _c ur re nt ad dr es s n ex t) ad dr es s se t_ cu rr en t(a dd re ss ne xt { a dd re ss p re v = c ur re nt ad dr es s pr ev cu rr en t; c ur re nt = n ex t; cu rr en t ne xt r et ur n p re v; re tu rn pr ev } Other plausible operations, such as comparison (== and !=), are not defined. However, the user can define such operators (Chapter 11). The size of an object of a structure type is not necessarily the sum of the sizes of its members. This is because many machines require objects of certain types to be allocated on architecture- dependent boundaries or handle such objects much more efficiently if they are. For example, inte- gers are often allocated on word boundaries. On such machines, objects are said to have to be aligned properly. This leads to ‘‘holes’’ in the structures. For example, on many machines,
    113. Section 5.7 Structures 103 s iz eo f(a dd re ss is 2 4, and not 2 2 as might be expected. You can minimize wasted space by sim- si ze of ad dr es s) 24 22 ply ordering members by size (largest member first). However, it is usually best to order members for readability and sort them by size only if there is a demonstrated need to optimize. The name of a type becomes available for use immediately after it has been encountered and not just after the complete declaration has been seen. For example: s tr uc t L in k { st ru ct Li nk L in k* p re vi ou s; Li nk pr ev io us L in k* s uc ce ss or Li nk su cc es so r; }; It is not possible to declare new objects of a structure type until the complete declaration has been seen. For example: st ru ct No _g oo d s tr uc t N o_ go od { No _g oo d me mb er N o_ go od m em be r; // error: recursive definition }; No _g oo d. This is an error because the compiler is not able to determine the size of N o_ go od To allow two (or more) structure types to refer to each other, we can declare a name to be the name of a structure type. For example: s tr uc t L is t; st ru ct Li st // to be defined later s tr uc t L in k { st ru ct Li nk L in k* p re Li nk pr e; L in k* s uc Li nk su c; Li st me mb er _o f; L is t* m em be r_ of }; s tr uc t L is t { st ru ct Li st L in k* h ea d; Li nk he ad }; Without the first declaration of L is t, use of L is t in the declaration of L in k would have caused a syn- Li st Li st Li nk tax error. The name of a structure type can be used before the type is defined as long as that use does not require the name of a member or the size of the structure to be known. For example: c la ss S cl as s S; // ‘S’ is the name of some type e xt er n S a ex te rn a; Sf ;f() v oi d g S); vo id g(S S h S*); S* h(S However, many such declarations cannot be used unless the type S is defined: v oi d k S* p vo id k(S p) { Saa; // error: S not defined; size needed to allocate
    114. 104 Pointers, Arrays, and Structures Chapter 5 f; f() // error: S not defined; size needed to return value g a); g(a // error: S not defined; size needed to pass argument p m=7 p->m 7; // error: S not defined; member name not known S q = h p); S* h(p // ok: pointers can be allocated and passed q m=7 q->m 7; // error: S not defined; member name not known } A s tr uc t is a simple form of a c la ss (Chapter 10). st ru ct cl as s For reasons that reach into the pre-history of C, it is possible to declare a s tr uc t and a non- st ru ct structure with the same name in the same scope. For example: s tr uc t s ta t { /* ... */ }; st ru ct st at i nt s ta t(c ha r* n am e, s tr uc t s ta t* b uf ; in t st at ch ar na me st ru ct st at bu f) In that case, the plain name (s ta t) is the name of the non-structure, and the structure must be st at referred to with the prefix s tr uc t. Similarly, the keywords c la ss u ni on (§C.8.2), and e nu m (§4.8) st ru ct cl as s, un io n en um can be used as prefixes for disambiguation. However, it is best not to overload names to make that necessary. 5.7.1 Type Equivalence [ptr.equiv] Two structures are different types even when they have the same members. For example, s tr uc t S 1 { i nt a }; st ru ct S1 in t a; s tr uc t S 2 { i nt a }; st ru ct S2 in t a; are two different types, so S1 x S1 x; S 2 y = x // error: type mismatch S2 x; Structure types are also different from fundamental types, so S1 x S1 x; i nt i = x // error: type mismatch in t x; Every s tr uc t must have a unique definition in a program (§9.2.3). st ru ct 5.8 Advice [ptr.advice] [1] Avoid nontrivial pointer arithmetic; §5.3. [2] Take care not to write beyond the bounds of an array; §5.3.1. [3] Use 0 rather than N UL L; §5.1.1. NU LL [4] Use v ec to r and v al ar ra y rather than built-in (C-style) arrays; §5.3.1. ve ct or va la rr ay [5] Use s tr in g rather than zero-terminated arrays of c ha r; §5.3. st ri ng ch ar [6] Minimize use of plain reference arguments; §5.5. [7] Avoid v oi d* except in low-level code; §5.6. vo id [8] Avoid nontrivial literals (‘‘magic numbers’’) in code. Instead, define and use symbolic con- stants; §4.8, §5.4.
    115. Section 5.9 Exercises 105 5.9 Exercises [ptr.exercises] 1. (∗1) Write declarations for the following: a pointer to a character, an array of 10 integers, a ref- erence to an array of 10 integers, a pointer to an array of character strings, a pointer to a pointer to a character, a constant integer, a pointer to a constant integer, and a constant pointer to an integer. Initialize each one. 2. (∗1.5) What, on your system, are the restrictions on the pointer types c ha r*, i nt and v oi d*? ch ar in t*, vo id For example, may an i nt have an odd value? Hint: alignment. in t* 3. (∗1) Use t yp ed ef to define the types u ns ig ne d c ha r, c on st u ns ig ne d c ha r, pointer to integer, ty pe de f un si gn ed ch ar co ns t un si gn ed ch ar pointer to pointer to c ha r, pointer to arrays of c ha r, array of 7 pointers to i nt pointer to an array ch ar ch ar in t, of 7 pointers to i nt and array of 8 arrays of 7 pointers to i nt in t, in t. 4. (∗1) Write a function that swaps (exchanges the values of) two integers. Use i nt as the argu- in t* ment type. Write another swap function using i nt as the argument type. in t& 5. (∗1.5) What is the size of the array s tr in the following example: st r c ha r s tr = \"a s ho rt s tr in g\"; ch ar st r[] a sh or t st ri ng What is the length of the string \" a s ho rt s tr in g\" \"a sh or t st ri ng \"? 6. (∗1) Define functions f ch ar g ch ar f(c ha r), g(c ha r&), and h co ns t c ha r&). Call them with the arguments h(c on st ch ar ´a 4 9, 3 30 0, c u c, and s c, where c is a c ha r, u c is an u ns ig ne d c ha r, and s c is a s ig ne d a´, 49 33 00 c, uc sc ch ar uc un si gn ed ch ar sc si gn ed c ha r. Which calls are legal? Which calls cause the compiler to introduce a temporary variable? ch ar 7. (∗1.5) Define a table of the names of months of the year and the number of days in each month. Write out that table. Do this twice; once using an array of c ha r for the names and an array for ch ar the number of days and once using an array of structures, with each structure holding the name of a month and the number of days in it. 8. (∗2) Run some tests to see if your compiler really generates equivalent code for iteration using pointers and iteration using indexing (§5.3.1). If different degrees of optimization can be requested, see if and how that affects the quality of the generated code. 9. (∗1.5) Find an example where it would make sense to use a name in its own initializer. 10. (∗1) Define an array of strings in which the strings contain the names of the months. Print those strings. Pass the array to a function that prints those strings. 11. (∗2) Read a sequence of words from input. Use Q ui t as a word that terminates the input. Print Qu it the words in the order they were entered. Don’t print a word twice. Modify the program to sort the words before printing them. 12. (∗2) Write a function that counts the number of occurrences of a pair of letters in a s tr in g and st ri ng another that does the same in a zero-terminated array of c ha r (a C-style string). For example, ch ar the pair \"ab\" appears twice in \"xabaacbaxabb\". 13. (∗1.5) Define a s tr uc t D at e to keep track of dates. Provide functions that read D at es from st ru ct Da te Da te input, write D at es to output, and initialize a D at e with a date. Da te Da te
    116. 106 Pointers, Arrays, and Structures Chapter 5 .
    117. ________________________________________ ________________________________________________________________________________________________________________________________________________________________ 6 ________________________________________ ________________________________________________________________________________________________________________________________________________________________ Expressions and Statements Premature optimization is the root of all evil. – D. Knuth On the other hand, we cannot ignore efficiency. – Jon Bentley Desk calculator example — input — command line arguments — expression summary — logical and relational operators — increment and decrement — free store — explicit type conversion — statement summary — declarations — selection statements — decla- rations in conditions — iteration statements — the infamous g ot o — comments and go to indentation — advice — exercises. 6.1 A Desk Calculator [expr.calculator] Statements and expressions are introduced by presenting a desk calculator program that provides the four standard arithmetic operations as infix operators on floating-point numbers. The user can also define variables. For example, given the input r=2 52.5 a re a = p i * r * r ar ea pi (pi is predefined) the calculator program will write 25 2.5 1 9.6 35 19 63 5 where 2 5 is the result of the first line of input and 1 9.6 35 is the result of the second. 2.5 19 63 5
    118. 108 Expressions and Statements Chapter 6 The calculator consists of four main parts: a parser, an input function, a symbol table, and a driver. Actually, it is a miniature compiler in which the parser does the syntactic analysis, the input function handles input and lexical analysis, the symbol table holds permanent information, and the driver handles initialization, output, and errors. We could add many features to this calculator to make it more useful (§6.6[20]), but the code is long enough as it is, and most features would just add code without providing additional insight into the use of C++. 6.1.1 The Parser [expr.parser] Here is a grammar for the language accepted by the calculator: p ro gr am pr og ra m: E ND EN D // END is end-of-input ex pr _l is t EN D e xp r_ li st E ND ex pr _l is t: e xp r_ li st e xp re ss io n P RI NT ex pr es si on PR IN T // PRINT is semicolon ex pr es si on PR IN T ex pr _l is t e xp re ss io n P RI NT e xp r_ li st e xp re ss io n: ex pr es si on e xp re ss io n + t er m ex pr es si on te rm e xp re ss io n - t er m ex pr es si on te rm t er m te rm t er m: te rm t er m / p ri ma ry te rm pr im ar y t er m * p ri ma ry te rm pr im ar y p ri ma ry pr im ar y p ri ma ry pr im ar y: N UM BE R NU MB ER N AM E NA ME N AM E = e xp re ss io n NA ME ex pr es si on - p ri ma ry pr im ar y ( e xp re ss io n ) ex pr es si on In other words, a program is a sequence of expressions separated by semicolons. The basic units of an expression are numbers, names, and the operators *, /, +, - (both unary and binary), and =. Names need not be declared before use. The style of syntax analysis used is usually called recursive descent; it is a popular and straight- forward top-down technique. In a language such as C++, in which function calls are relatively cheap, it is also efficient. For each production in the grammar, there is a function that calls other functions. Terminal symbols (for example, E ND N UM BE R, +, and -) are recognized by the lexi- EN D, NU MB ER cal analyzer, g et _t ok en ge t_ to ke n(); and nonterminal symbols are recognized by the syntax analyzer func- tions, e xp r(), t er m(), and p ri m(). As soon as both operands of a (sub)expression are known, the ex pr te rm pr im expression is evaluated; in a real compiler, code could be generated at this point. The parser uses a function g et _t ok en ge t_ to ke n() to get input. The value of the most recent call of g et _t ok en cu rr _t ok cu rr _t ok ge t_ to ke n() can be found in the global variable c ur r_ to k. The type of c ur r_ to k is the enumera- tion T ok en _v al ue To ke n_ va lu e:
    119. Section 6.1.1 The Parser 109 e nu m T ok en _v al ue { en um To ke n_ va lu e N AM E, NA ME N UM BE R, NU MB ER E ND EN D, P LU S=´+´, PL US M IN US MI NU S=´-´, M UL MU L=´*´, D IV DI V=´/´, P RI NT PR IN T=´;´, A SS IG N=´=´, L P=´(´, AS SI GN LP R P=´)´ RP }; T ok en _v al ue c ur r_ to k = P RI NT To ke n_ va lu e cu rr _t ok PR IN T; Representing each token by the integer value of its character is convenient and efficient and can be a help to people using debuggers. This works as long as no character used as input has a value used as an enumerator – and no character set I know of has a printing character with a single-digit inte- cu rr _t ok ger value. I chose P RI NT as the initial value for c ur r_ to k because that is the value it will have PR IN T after the calculator has evaluated an expression and displayed its value. Thus, I ‘‘start the system’’ in a normal state to minimize the chance of errors and the need for special startup code. Each parser function takes a b oo l (§4.2) argument indicating whether the function needs to call bo ol g et _t ok en to get the next token. Each parser function evaluates ‘‘its’’ expression and returns the ge t_ to ke n() value. The function e xp r() handles addition and subtraction. It consists of a single loop that looks ex pr for terms to add or subtract: d ou bl e e xp r(b oo l g et do ub le ex pr bo ol ge t) // add and subtract { d ou bl e l ef t = t er m(g et ; do ub le le ft te rm ge t) f or (;;) fo r // ‘‘forever’’ sw it ch cu rr _t ok s wi tc h (c ur r_ to k) { c as e P LU S: ca se PL US l ef t += t er m(t ru e); le ft te rm tr ue b re ak br ea k; c as e M IN US ca se MI NU S: l ef t -= t er m(t ru e); le ft te rm tr ue b re ak br ea k; d ef au lt de fa ul t: r et ur n l ef t; re tu rn le ft } } This function really does not do much itself. In a manner typical of higher-level functions in a large program, it calls other functions to do the work. The switch-statement tests the value of its condition, which is supplied in parentheses after the s wi tc h keyword, against a set of constants. The break-statements are used to exit the switch- sw it ch statement. The constants following the c as e labels must be distinct. If the value tested does not ca se match any c as e label, the d ef au lt is chosen. The programmer need not provide a d ef au lt ca se de fa ul t de fa ul t. Note that an expression such as 2 3+4 is evaluated as (2 3)+4 as specified in the grammar. 2-3 4 2-3 4, The curious notation f or fo r(;;) is the standard way to specify an infinite loop; you could pro- nounce it ‘‘forever.’’ It is a degenerate form of a for-statement (§6.3.3); w hi le tr ue is an alterna- wh il e(t ru e) tive. The switch-statement is executed repeatedly until something different from + and - is found, and then the return-statement in the default case is executed. The operators += and -= are used to handle the addition and subtraction; l ef t=l ef t+t er m() and le ft le ft te rm
    120. 110 Expressions and Statements Chapter 6 l ef t=l ef t-t er m() could have been used without changing the meaning of the program. However, le ft le ft te rm l ef t+=t er m() and l ef t-=t er m() not only are shorter but also express the intended operation le ft te rm le ft te rm directly. Each assignment operator is a separate lexical token, so a + = 1 is a syntax error because 1; of the space between the + and the =. Assignment operators are provided for the binary operators + - * / % & | ^ << >> so that the following assignment operators are possible = += -= *= /= %= &= |= ^= <<= >>= The % is the modulo, or remainder, operator; &, |, and ^ are the bitwise logical operators AND, OR, and exclusive OR; << and >> are the left shift and right shift operators; §6.2 summarizes the operators and their meanings. For a binary operator @ applied to operands of built-in types, an expression x @= y means x =x @y except that x is evaluated once only. x@ =y x= x@ y, Chapter 8 and Chapter 9 discuss how to organize a program as a set of modules. With one exception, the declarations for this calculator example can be ordered so that everything is declared exactly once and before it is used. The exception is e xp r(), which calls t er m(), which calls ex pr te rm p ri m(), which in turn calls e xp r(). This loop must be broken somehow. A declaration pr im ex pr d ou bl e e xp r(b oo l); do ub le ex pr bo ol before the definition of p ri m() will do nicely. pr im Function t er m() handles multiplication and division in the same way e xp r() handles addition te rm ex pr and subtraction: d ou bl e t er m(b oo l g et do ub le te rm bo ol ge t) // multiply and divide { d ou bl e l ef t = p ri m(g et ; do ub le le ft pr im ge t) f or (;;) fo r sw it ch cu rr _t ok s wi tc h (c ur r_ to k) { c as e M UL ca se MU L: l ef t *= p ri m(t ru e); le ft pr im tr ue b re ak br ea k; c as e D IV ca se DI V: i f (d ou bl e d = p ri m(t ru e)) { if do ub le pr im tr ue l ef t /= d le ft d; b re ak br ea k; } r et ur n e rr or di vi de b y 0 ; re tu rn er ro r(\"d iv id e by 0\") d ef au lt de fa ul t: r et ur n l ef t; re tu rn le ft } } The result of dividing by zero is undefined and usually disastrous. We therefore test for 0 before dividing and call e rr or if we detect a zero divisor. The function e rr or is described in §6.1.4. er ro r() er ro r() The variable d is introduced into the program exactly where it is needed and initialized immedi- ately. The scope of a name introduced in a condition is the statement controlled by that condition,
    121. Section 6.1.1 The Parser 111 and the resulting value is the value of the condition (§6.3.2.1). Consequently, the division and assignment l ef t/=d is done if and only if d is nonzero. le ft d The function p ri m() handling a primary is much like e xp r() and t er m(), except that because pr im ex pr te rm we are getting lower in the call hierarchy a bit of real work is being done and no loop is necessary: do ub le nu mb er _v al ue d ou bl e n um be r_ va lu e; st ri ng st ri ng _v al ue s tr in g s tr in g_ va lu e; d ou bl e p ri m(b oo l g et do ub le pr im bo ol ge t) // handle primaries { i f (g et g et _t ok en ; if ge t) ge t_ to ke n() sw it ch cu rr _t ok s wi tc h (c ur r_ to k) { c as e N UM BE R: ca se NU MB ER // floating-point constant nu mb er _v al ue d ou bl e v = n um be r_ va lu e; do ub le { g et _t ok en ; ge t_ to ke n() r et ur n v re tu rn v; } c as e N AM E: ca se NA ME d ou bl e& v = t ab le st ri ng _v al ue ; do ub le ta bl e[s tr in g_ va lu e] { i f (g et _t ok en if ge t_ to ke n() == A SS IG N) v = e xp r(t ru e); AS SI GN ex pr tr ue r et ur n v re tu rn v; } c as e M IN US ca se MI NU S: // unary minus r et ur n -p ri m(t ru e); re tu rn pr im tr ue c as e L P: ca se LP d ou bl e e = e xp r(t ru e); do ub le ex pr tr ue { if cu rr _t ok i f (c ur r_ to k != R P) r et ur n e rr or RP re tu rn er ro r(\") e xp ec te d\"); ex pe ct ed g et _t ok en ; ge t_ to ke n() // eat ’)’ r et ur n e re tu rn e; } d ef au lt de fa ul t: r et ur n e rr or pr im ar y e xp ec te d\"); re tu rn er ro r(\"p ri ma ry ex pe ct ed } } When a N UM BE R (that is, an integer or floating-point literal) is seen, its value is returned. The NU MB ER input routine g et _t ok en nu mb er _v al ue ge t_ to ke n() places the value in the global variable n um be r_ va lu e. Use of a global variable in a program often indicates that the structure is not quite clean – that some sort of opti- mization has been applied. So it is here. Ideally, a lexical token consists of two parts: a value spec- ifying the kind of token (a T ok en _v al ue in this program) and (when needed) the value of the token. To ke n_ va lu e cu rr _t ok nu mb er _v al ue Here, there is only a single, simple variable, c ur r_ to k, so the global variable n um be r_ va lu e is needed to hold the value of the last N UM BE R read. Eliminating this spurious global variable is left NU MB ER nu mb er _v al ue as an exercise (§6.6[21]). Saving the value of n um be r_ va lu e in the local variable v before calling g et _t ok en ge t_ to ke n() is not really necessary. For every legal input, the calculator always uses one number in the computation before reading another from input. However, saving the value and displaying it correctly after an error helps the user. nu mb er _v al ue In the same way that the value of the last N UM BE R is kept in n um be r_ va lu e, the character NU MB ER st ri ng _v al ue string representation of the last N AM E seen is kept in s tr in g_ va lu e. Before doing anything to a NA ME
    122. 112 Expressions and Statements Chapter 6 name, the calculator must first look ahead to see if it is being assigned to or simply read. In both cases, the symbol table is consulted. The symbol table is a m ap (§3.7.4, §17.4.1): ma p m ap st ri ng do ub le t ab le ma p<s tr in g,d ou bl e> ta bl e; That is, when t ab le is indexed by a s tr in g, the resulting value is the d ou bl e corresponding to the ta bl e st ri ng do ub le s tr in g. For example, if the user enters st ri ng r ad iu s = 6 37 8.3 88 ra di us 63 78 38 8; the calculator will execute d ou bl e& v = t ab le ra di us ; do ub le ta bl e[\"r ad iu s\"] // ... expr() calculates the value to be assigned ... v = 6 37 8.3 88 63 78 38 8; The reference v is used to hold on to the d ou bl e associated with r ad iu s while e xp r() calculates the do ub le ra di us ex pr value 6 37 8.3 88 from the input characters. 63 78 38 8 6.1.2 The Input Function [expr.input] Reading input is often the messiest part of a program. This is because a program must communi- cate with a person, it must cope with that person’s whims, conventions, and seemingly random errors. Trying to force the person to behave in a manner more suitable for the machine is often (rightly) considered offensive. The task of a low-level input routine is to read characters and com- pose higher-level tokens from them. These tokens are then the units of input for higher-level rou- tines. Here, low-level input is done by g et _t ok en ge t_ to ke n(). Writing a low-level input routine need not be an everyday task. Many systems provide standard functions for this. I build g et _t ok en in two stages. First, I provide a deceptively simple version that imposes a ge t_ to ke n() burden on the user. Next, I modify it into a slightly less elegant, but much easier to use, version. The idea is to read a character, use that character to decide what kind of token needs to be com- posed, and then return the T ok en _v al ue representing the token read. To ke n_ va lu e The initial statements read the first non-whitespace character into c h and check that the read ch operation succeeded: T ok en _v al ue g et _t ok en To ke n_ va lu e ge t_ to ke n() { c ha r c h = 0 ch ar ch 0; c in ch ci n>>c h; s wi tc h (c h) { sw it ch ch c as e 0 ca se 0: re tu rn cu rr _t ok EN D; r et ur n c ur r_ to k=E ND // assign and return By default, operator >> skips whitespace (that is, spaces, tabs, newlines, etc.) and leaves the value of c h unchanged if the input operation failed. Consequently, c h==0 indicates end of input. ch ch 0 Assignment is an operator, and the result of the assignment is the value of the variable assigned EN D cu rr _t ok to. This allows me to assign the value E ND to c ur r_ to k and return it in the same statement. Hav- ing a single statement rather than two is useful in maintenance. If the assignment and the return became separated in the code, a programmer might update the one and forget to update to the other.
    123. Section 6.1.2 The Input Function 113 Let us look at some of the cases separately before considering the complete function. The expression terminator ´;´, the parentheses, and the operators are handled simply by returning their values: c as e ´;´: ca se c as e ´*´: ca se c as e ´/´: ca se c as e ´+´: ca se c as e ´-´: ca se c as e ´(´: ca se c as e ´)´: ca se c as e ´=´: ca se r et ur n c ur r_ to k=T ok en _v al ue ch ; re tu rn cu rr _t ok To ke n_ va lu e(c h) Numbers are handled like this: c as e ´0 c as e ´1 ca se 0´: ca se 1´: c as e ´2 ca se 2´: c as e ´3 ca se 3´: c as e ´4 ca se 4´: c as e ´5 ca se 5´: c as e ´6 ca se 6´: c as e ´7 ca se 7´: c as e ´8 ca se 8´: c as e ´9 ca se 9´: c as e ´.´: ca se c in pu tb ac k(c h); ci n.p ut ba ck ch nu mb er _v al ue c in >> n um be r_ va lu e; ci n re tu rn cu rr _t ok NU MB ER r et ur n c ur r_ to k=N UM BE R; Stacking c as e labels horizontally rather than vertically is generally not a good idea because this ca se arrangement is harder to read. However, having one line for each digit is tedious. Because opera- tor >> is already defined for reading floating-point constants into a d ou bl e, the code is trivial. First do ub le the initial character (a digit or a dot) is put back into c in Then the constant can be read into ci n. nu mb er _v al ue n um be r_ va lu e. A name is handled similarly: d ef au lt de fa ul t: // NAME, NAME =, or error i f (i sa lp ha ch if is al ph a(c h)) { c in pu tb ac k(c h); ci n.p ut ba ck ch c in st ri ng _v al ue ci n>>s tr in g_ va lu e; re tu rn cu rr _t ok NA ME r et ur n c ur r_ to k=N AM E; } e rr or ba d t ok en ; er ro r(\"b ad to ke n\") re tu rn cu rr _t ok PR IN T; r et ur n c ur r_ to k=P RI NT The standard library function i sa lp ha (§20.4.2) is used to avoid listing every character as a sepa- is al ph a() st ri ng _v al ue rate c as e label. Operator >> applied to a string (in this case, s tr in g_ va lu e) reads until it hits white- ca se space. Consequently, a user must terminate a name by a space before an operator using the name as an operand. This is less than ideal, so we will return to this problem in §6.1.3. Here, finally, is the complete input function: T ok en _v al ue g et _t ok en To ke n_ va lu e ge t_ to ke n() { c ha r c h = 0 ch ar ch 0; c in ch ci n>>c h;
    124. 114 Expressions and Statements Chapter 6 s wi tc h (c h) { sw it ch ch c as e 0 ca se 0: re tu rn cu rr _t ok EN D; r et ur n c ur r_ to k=E ND c as e ´;´: ca se c as e ´*´: ca se c as e ´/´: ca se c as e ´+´: ca se c as e ´-´: ca se c as e ´(´: ca se c as e ´)´: ca se c as e ´=´: ca se r et ur n c ur r_ to k=T ok en _v al ue ch ; re tu rn cu rr _t ok To ke n_ va lu e(c h) c as e ´0 ca se 0´: c as e ´1 ca se 1´: c as e ´2 ca se 2´: c as e ´3 ca se 3´: c as e ´4 ca se 4´: c as e ´5 ca se 5´: c as e ´6 ca se 6´: c as e ´7 ca se 7´: c as e ´8 ca se 8´: c as e ´9 ca se 9´: c as e ´.´: ca se c in pu tb ac k(c h); ci n.p ut ba ck ch nu mb er _v al ue c in >> n um be r_ va lu e; ci n re tu rn cu rr _t ok NU MB ER r et ur n c ur r_ to k=N UM BE R; d ef au lt de fa ul t: // NAME, NAME =, or error i f (i sa lp ha ch { if is al ph a(c h)) c in pu tb ac k(c h); ci n.p ut ba ck ch c in st ri ng _v al ue ci n>>s tr in g_ va lu e; re tu rn cu rr _t ok NA ME r et ur n c ur r_ to k=N AM E; } e rr or ba d t ok en ; er ro r(\"b ad to ke n\") re tu rn cu rr _t ok PR IN T; r et ur n c ur r_ to k=P RI NT } } The conversion of an operator to its token value is trivial because the T ok en _v al ue of an operator To ke n_ va lu e was defined as the integer value of the operator (§4.8). 6.1.3 Low-level Input [expr.low] Using the calculator as defined so far reveals a few inconveniences. It is tedious to remember to add a semicolon after an expression in order to get its value printed, and having a name terminated by whitespace only is a real nuisance. For example, x 7 is an identifier – rather than the identifier x=7 x followed by the operator = and the number 7 Both problems are solved by replacing the type- 7. oriented default input operations in g et _t ok en with code that reads individual characters. ge t_ to ke n() First, we’ll make a newline equivalent to the semicolon used to mark the end of expression: T ok en _v al ue g et _t ok en To ke n_ va lu e ge t_ to ke n() { c ha r c h; ch ar ch d o { // skip whitespace except ’\\n’ do re tu rn cu rr _t ok EN D; i f(!c in ge t(c h)) r et ur n c ur r_ to k = E ND if ci n.g et ch } w hi le (c h!=´\\ n´ && i ss pa ce ch ; wh il e ch \\n is sp ac e(c h))
    125. Section 6.1.3 Low-level Input 115 s wi tc h (c h) { sw it ch ch c as e ´;´: ca se c as e ´\\ n´: ca se \\n re tu rn cu rr _t ok PR IN T; r et ur n c ur r_ to k=P RI NT A do-statement is used; it is equivalent to a while-statement except that the controlled statement is always executed at least once. The call c in ge t(c h) reads a single character from the standard ci n.g et ch input stream into c h. By default, g et ch ge t() does not skip whitespace the way o pe ra to r >> does. The op er at or test i f (!c in ge t(c h)) fails if no character can be read from c in in this case, E ND is returned to if ci n.g et ch ci n; EN D terminate the calculator session. The operator ! (NOT) is used because g et ge t() returns t ru e in case tr ue of success. The standard library function i ss pa ce is sp ac e() provides the standard test for whitespace (§20.4.2); i ss pa ce c) returns a nonzero value if c is a whitespace character and zero otherwise. The test is is sp ac e(c implemented as a table lookup, so using i ss pa ceis sp ac e() is much faster than testing for the individual whitespace characters. Similar functions test if a character is a digit – i sd ig it is di gi t() – a letter – i sa l- is al - p ha – or a digit or letter – i sa ln um ph a() is al nu m(). After whitespace has been skipped, the next character is used to determine what kind of lexical token is coming. The problem caused by >> reading into a string until whitespace is encountered is solved by reading one character at a time until a character that is not a letter or a digit is found: d ef au lt de fa ul t: // NAME, NAME=, or error i f (i sa lp ha ch if is al ph a(c h)) { st ri ng _v al ue ch s tr in g_ va lu e = c h; st ri ng _v al ue pu sh _b ac k(c h) w hi le (c in ge t(c h) && i sa ln um ch wh il e ci n.g et ch is al nu m(c h)) s tr in g_ va lu e.p us h_ ba ck ch ; c in pu tb ac k(c h); ci n.p ut ba ck ch re tu rn cu rr _t ok NA ME r et ur n c ur r_ to k=N AM E; } e rr or ba d t ok en ; er ro r(\"b ad to ke n\") re tu rn cu rr _t ok PR IN T; r et ur n c ur r_ to k=P RI NT Fortunately, these two improvements could both be implemented by modifying a single local sec- tion of code. Constructing programs so that improvements can be implemented through local mod- ifications only is an important design aim. 6.1.4 Error Handling [expr.error] Because the program is so simple, error handling is not a major concern. The error function simply counts the errors, writes out an error message, and returns: i nt n o_ of _e rr or s; in t no _o f_ er ro rs d ou bl e e rr or co ns t s tr in g& s do ub le er ro r(c on st st ri ng s) { n o_ of _e rr or s++; no _o f_ er ro rs c er r << \"e rr or \" << s << ´\\ n´; ce rr er ro r: \\n r et ur n 1 re tu rn 1; } The stream c er r is an unbuffered output stream usually used to report errors (§21.2.1). ce rr
    126. 116 Expressions and Statements Chapter 6 The reason for returning a value is that errors typically occur in the middle of the evaluation of an expression, so we should either abort that evaluation entirely or return a value that is unlikely to cause subsequent errors. The latter is adequate for this simple calculator. Had g et _t ok en ge t_ to ke n() kept track of the line numbers, e rr or er ro r() could have informed the user approximately where the error occurred. This would be useful when the calculator is used noninteractively (§6.6[19]). Often, a program must be terminated after an error has occurred because no sensible way of continuing has been devised. This can be done by calling e xi t(), which first cleans up things like ex it output streams and then terminates the program with its argument as the return value (§9.4.1.1). More stylized error-handling mechanisms can be implemented using exceptions (see §8.3, Chapter 14), but what we have here is quite suitable for a 150-line calculator. 6.1.5 The Driver [expr.driver] With all the pieces of the program in place, we need only a driver to start things. In this simple example, m ai n() can do that: ma in i nt m ai n() in t ma in { t ab le pi ta bl e[\"p i\"] = 3 14 15 92 65 35 89 79 32 38 5; 3.1 41 59 26 53 58 97 93 23 85 // insert predefined names t ab le e\"] = 2 71 82 81 82 84 59 04 52 35 4; ta bl e[\"e 2.7 18 28 18 28 45 90 45 23 54 w hi le (c in { wh il e ci n) g et _t ok en ; ge t_ to ke n() if cu rr _t ok i f (c ur r_ to k == E ND b re ak EN D) br ea k; if cu rr _t ok i f (c ur r_ to k == P RI NT c on ti nu e; PR IN T) co nt in ue c ou t << e xp r(f al se << ´\\ n´; co ut ex pr fa ls e) \\n } r et ur n n o_ of _e rr or s; re tu rn no _o f_ er ro rs } Conventionally, m ai n() should return zero if the program terminates normally and nonzero other- ma in wise (§3.2). Returning the number of errors accomplishes this nicely. As it happens, the only initialization needed is to insert the predefined names into the symbol table. The primary task of the main loop is to read expressions and write out the answer. This is achieved by the line: c ou t << e xp r(f al se << ´\\ n´; co ut ex pr fa ls e) \\n The argument f al se tells e xp r() that it does not need to call g et _t ok en fa ls e ex pr ge t_ to ke n() to get a current token on which to work. Testing c in each time around the loop ensures that the program terminates if something goes ci n wrong with the input stream, and testing for E ND ensures that the loop is correctly exited when EN D g et _t ok en encounters end-of-file. A break-statement exits its nearest enclosing switch-statement ge t_ to ke n() or loop (that is, a for-statement, while-statement, or do-statement). Testing for P RI NT (that is, for PR IN T ´\\ n´ and ´;´) relieves e xp r() of the responsibility for handling empty expressions. A continue- \\n ex pr statement is equivalent to going to the very end of a loop, so in this case
    127. Section 6.1.5 The Driver 117 w hi le (c in { wh il e ci n) // ... if cu rr _t ok i f (c ur r_ to k == P RI NT c on ti nu e; PR IN T) co nt in ue c ou t << e xp r(f al se << ´\\ n´; co ut ex pr fa ls e) \\n } is equivalent to w hi le (c in { wh il e ci n) // ... if cu rr _t ok i f (c ur r_ to k != P RI NT PR IN T) c ou t << e xp r(f al se << ´\\ n´; co ut ex pr fa ls e) \\n } 6.1.6 Headers [expr.headers] The calculator uses standard library facilities. Therefore, appropriate headers must be #i nc lu de to in cl ud ed complete the program: #i nc lu de io st re am in cl ud e<i os tr ea m> // I/O #i nc lu de st ri ng in cl ud e<s tr in g> // strings #i nc lu de ma p> in cl ud e<m ap // map #i nc lu de cc ty pe in cl ud e<c ct yp e> // isalpha(), etc. All of these headers provide facilities in the s td namespace, so to use the names they provide we st d must either use explicit qualification with s td : or bring the names into the global namespace by st d: u si ng n am es pa ce s td us in g na me sp ac e st d; To avoid confusing the discussion of expressions with modularity issues, I did the latter. Chapter 8 and Chapter 9 discuss ways of organizing this calculator into modules using namespaces and how to organize it into source files. On many systems, standard headers have equivalents with a .h suf- h fix that declare the classes, functions, etc., and place them in the global namespace (§9.2.1, §9.2.4, §B.3.1). 6.1.7 Command-Line Arguments [expr.command] After the program was written and tested, I found it a bother to first start the program, then type the expressions, and finally quit. My most common use was to evaluate a single expression. If that expression could be presented as a command-line argument, a few keystrokes could be avoided. A program starts by calling m ai n() (§3.2, §9.4). When this is done, m ai n() is given two ma in ma in arguments specifying the number of arguments, usually called a rg c, and an array of arguments, ar gc usually called a rg v. The arguments are character strings, so the type of a rg v is c ha r*[a rg c+1 ar gv ar gv ch ar ar gc 1]. The name of the program (as it occurs on the command line) is passed as a rg v[0 so a rg c is ar gv 0], ar gc always at least 1 The list of arguments is zero-terminated; that is, a rg v[a rg c]==0 For example, 1. ar gv ar gc 0. for the command d c 1 50 1.1 93 4 dc 15 0/1 19 34 the arguments have these values:
    128. 118 Expressions and Statements Chapter 6 a rg c: ar gc 2 a rg v: ar gv 0 . . \"d c\" dc \"1 50 /1 .1 93 4\" 15 0/ 1. 19 34 Because the conventions for calling m ai n() are shared with C, C-style arrays and strings are used. ma in It is not difficult to get hold of a command-line argument. The problem is how to use it with minimal reprogramming. The idea is to read from the command string in the same way that we read from the input stream. A stream that reads from a string is unsurprisingly called an i st ri ng st re am Unfortunately, there is no elegant way of making c in refer to an i st ri ng st re am is tr in gs tr ea m. ci n is tr in gs tr ea m. Therefore, we must find a way of getting the calculator input functions to refer to an i st ri ng st re am is tr in gs tr ea m. Furthermore, we must find a way of getting the calculator input functions to refer to an i st ri ng st re am or to c in depending on what kind of command-line argument we supply. is tr in gs tr ea m ci n A simple solution is to introduce a global pointer i np ut that points to the input stream to be used in pu t and have every input routine use that: i st re am i np ut // pointer to input stream is tr ea m* in pu t; i nt m ai n(i nt a rg c, c ha r* a rg v[]) in t ma in in t ar gc ch ar ar gv { s wi tc h (a rg c) { sw it ch ar gc c as e 1 ca se 1: // read from standard input i np ut = &c in in pu t ci n; b re ak br ea k; c as e 2 ca se 2: // read argument string i np ut = n ew i st ri ng st re am ar gv 1]); in pu t ne w is tr in gs tr ea m(a rg v[1 b re ak br ea k; d ef au lt de fa ul t: e rr or to o m an y a rg um en ts ; er ro r(\"t oo ma ny ar gu me nt s\") r et ur n 1 re tu rn 1; } t ab le pi = 3 14 15 92 65 35 89 79 32 38 5; ta bl e[\"p i\"] 3.1 41 59 26 53 58 97 93 23 85 // insert predefined names t ab le e\"] = 2 71 82 81 82 84 59 04 52 35 4; ta bl e[\"e 2.7 18 28 18 28 45 90 45 23 54 w hi le (*i np ut { wh il e in pu t) g et _t ok en ; ge t_ to ke n() if cu rr _t ok i f (c ur r_ to k == E ND b re ak EN D) br ea k; if cu rr _t ok i f (c ur r_ to k == P RI NT c on ti nu e; PR IN T) co nt in ue c ou t << e xp r(f al se << ´\\ n´; co ut ex pr fa ls e) \\n } i f (i np ut != &c in d el et e i np ut if in pu t ci n) de le te in pu t; r et ur n n o_ of _e rr or s; re tu rn no _o f_ er ro rs }
    129. Section 6.1.7 Command-Line Arguments 119 An i st ri ng st re am is a kind of i st re am that reads from its character string argument (§21.5.3). is tr in gs tr ea m is tr ea m Upon reaching the end of its string, an i st ri ng st re am fails exactly like other streams do when they is tr in gs tr ea m hit the end of input (§3.6, §21.3.3). To use an i st ri ng st re am you must include <s st re am is tr in gs tr ea m, ss tr ea m>. It would be easy to modify m ai n() to accept several command-line arguments, but this does ma in not appear to be necessary, especially as several expressions can be passed as a single argument: d c \"r at e=1 19 34 15 0/r at e;1 9.7 5/r at e;2 17 ra te dc ra te 1.1 93 4;1 50 ra te 19 75 ra te 21 7/r at e\" I use quotes because ; is the command separator on my UNIX systems. Other systems have differ- ent conventions for supplying arguments to a program on startup. It was inelegant to modify all of the input routines to use *i np ut rather than c in to gain the flex- in pu t ci n ibility to use alternative sources of input. The change could have been avoided had I shown fore- sight by introducing something like i np ut from the start. A more general and useful view is to note in pu t that the source of input really should be the parameter of a calculator module. That is, the funda- mental problem with this calculator example is that what I refer to as ‘‘the calculator’’ is only a col- lection of functions and data. There is no module (§2.4) or object (§2.5.2) that explicitly represents the calculator. Had I set out to design a calculator module or a calculator type, I would naturally have considered what its parameters should be (§8.5[3], §10.6[16]). 6.1.8 A Note on Style [expr.style] To programmers unacquainted with associative arrays, the use of the standard library m ap as the ma p symbol table seems almost like cheating. It is not. The standard library and other libraries are meant to be used. Often, a library has received more care in its design and implementation than a programmer could afford for a handcrafted piece of code to be used in just one program. Looking at the code for the calculator, especially at the first version, we can see that there isn’t much traditional C-style, low-level code presented. Many of the traditional tricky details have been replaced by uses of standard library classes such as o st re am s tr in g, and m ap (§3.4, §3.5, §3.7.4, os tr ea m, st ri ng ma p Chapter 17). Note the relative scarcity of arithmetic, loops, and even assignments. This is the way things ought to be in code that doesn’t manipulate hardware directly or implement low-level abstractions. 6.2 Operator Summary [expr.operators] This section presents a summary of expressions and some examples. Each operator is followed by one or more names commonly used for it and an example of its use. In these tables, a class_name is the name of a class, a member is a member name, an object is an expression yielding a class object, a pointer is an expression yielding a pointer, an expr is an expression, and an lvalue is an expression denoting a nonconstant object. A type can be a fully general type name (with *, (), etc.) only when it appears in parentheses; elsewhere, there are restrictions (§A.5). The syntax of expressions is independent of operand types. The meanings presented here apply when the operands are of built-in types (§4.1.1). In addition, you can define meanings for operators applied to operands of user-defined types (§2.5.2, Chapter 11).
    130. 120 Expressions and Statements Chapter 6 _ ____________________________________________________________  ____________________________________________________________ _ ____________________________________________________________ _ Operator Summary   scope resolution class_name :: member    scope resolution  namespace_name :: member  global  :: name  global ____________________________________________________________ _ :: qualified-name    member selection object . member   member selection  pointer -> member  subscripting  pointer [ expr ]  function call  expr ( expr_list )  value construction  type ( expr_list )    post increment lvalue ++   post decrement  lvalue --  type identification  t yp ei d ( type ) ty pe id  run-time type identification  t yp ei d ( expr ) ty pe id  run-time checked conversion  d yn am ic _c as t < type > ( expr ) dy na mi c_ ca st   st at ic _c as t  compile-time checked conversion s ta ti c_ ca st < type > ( expr )  r ei nt er pr et _c as t < type > ( expr )   unchecked conversion re in te rp re t_ ca st  co ns t ____________________________________________________________ c on st _c as t < type > ( expr ) _c on st conversion co ns t_ ca st  size of object  s iz eo f expr si ze of    size of type s iz eo f ( type ) si ze of   pre increment  ++ lvalue  pre decrement  -- lvalue  complement  ~ expr  not  ! expr    unary minus - expr   unary plus  + expr  address of  & lvalue  dereference  ∗ expr  create (allocate)  n ew type ne w    create (allocate and initialize) n ew type ( expr-list ) ne w   create (place)  n ew ( expr-list ) type ne w  create (place and initialize) n ew ( expr-list ) type ( expr-list )  ne w  destroy (de-allocate)  d el et e pointer de le te  destroy array  d el et e[] pointer de le te   _cast (type conversion) ____________________________________________________________ ( type ) expr   member selection  object .* pointer-to-member  ____________________________________________________________ _member selection pointer ->* pointer-to-member   expr ∗ expr  multiply   divide  expr / expr  modulo (remainder) ____________________________________________________________  _  expr % expr
    131. Section 6.2 Operator Summary 121 ________________________________________ ________________________________________  ________________________________________ Operator Summary (continued)   add (plus) expr + expr   ________________________________________  subtract (minus) expr - expr  shift left  expr << expr  shift right  ________________________________________ expr >> expr   less than  expr < expr  less than or equal  expr <= expr  greater than  expr > expr  greater than or equal  ________________________________________ expr >= expr   equal  expr == expr ________________________________________  not equal expr != expr  bitwise AND  ________________________________________ expr & expr  ________________________________________  bitwise exclusive OR expr ^ expr ________________________________________  bitwise inclusive OR expr | expr   ________________________________________ logical AND expr && expr  ________________________________________  logical inclusive OR expr || expr  simple assignment  lvalue = expr   lvalue ∗= expr multiply and assign    divide and assign  lvalue /= expr  modulo and assign  lvalue %= expr  add and assign  lvalue += expr  subtract and assign  lvalue -= expr   shift left and assign lvalue <<= expr    shift right and assign lvalue >>= expr    AND and assign lvalue &= expr  inclusive OR and assign  lvalue |= expr  exclusive OR and assign  ________________________________________ lvalue ^= expr  ________________________________________  conditional expression expr ? expr : expr _______________________________________ _ throw exception t hr ow expr th ro w    comma (sequencing) ________________________________________ expr , expr Each box holds operators with the same precedence. Operators in higher boxes have higher prece- dence than operators in lower boxes. For example: a b*c means a b*c rather than (a b)*c a+b c a+(b c) a+b c because * has higher precedence than +. Unary operators and assignment operators are right-associative; all others are left-associative. For example, a b=c means a b=c a b+c means (a b)+c and *p a=b c a=(b c), a+b c a+b c, p++ means *(p p++), not p)++. (*p A few grammar rules cannot be expressed in terms of precedence (also known as binding strength) and associativity. For example, a b<c d=e f=g means a a=b c?d e:f g a=((b c)?(d e):(f g)), b<c d=e f=g but you need to look at the grammar (§A.5) to determine that.
    132. 122 Expressions and Statements Chapter 6 6.2.1 Results [expr.res] The result types of arithmetic operators are determined by a set of rules known as ‘‘the usual arith- metic conversions’’ (§C.6.3). The overall aim is to produce a result of the ‘‘largest’’ operand type. For example, if a binary operator has a floating-point operand, the computation is done using floating-point arithmetic and the result is a floating-point value. If it has a l on g operand, the com- lo ng putation is done using long integer arithmetic, and the result is a l on g. Operands that are smaller lo ng than an i nt (such as b oo l and c ha r) are converted to i nt before the operator is applied. in t bo ol ch ar in t The relational operators, ==, <=, etc., produce Boolean results. The meaning and result type of user-defined operators are determined by their declarations (§11.2). Where logically feasible, the result of an operator that takes an lvalue operand is an lvalue denoting that lvalue operand. For example: v oi d f in t x i nt y vo id f(i nt x, in t y) { i nt j = x = y in t y; // the value of x=y is the value of x after the assignment i nt p = &++x in t* x; // p points to x i nt q = &(x in t* x++); // error: x++ is not an lvalue (it is not the value stored in x) i nt p p = &(x y?x y); in t* pp x>y x:y // address of the int with the larger value } If both the second and third operands of ?: are lvalues and have the same type, the result is of that type and is an lvalue. Preserving lvalues in this way allows greater flexibility in using operators. This is particularly useful when writing code that needs to work uniformly and efficiently with both built-in and user-defined types (e.g., when writing templates or programs that generate C++ code). si ze _t The result of s iz eo f is of an unsigned integral type called s iz e_ t defined in <c st dd ef si ze of cs td de f>. The result of pointer subtraction is of a signed integral type called p tr di ff _t defined in <c st dd ef pt rd if f_ t cs td de f>. Implementations do not have to check for arithmetic overflow and hardly any do. For example: v oi d f vo id f() { i nt i = 1 in t 1; w hi le (0 < i i wh il e 0 i) i++; c ou t << \"i h as b ec om e n eg at iv e!\" << i << ´\\ n´; co ut i ha s be co me ne ga ti ve \\n } This will (eventually) try to increase i past the largest integer. What happens then is undefined, but typically the value ‘‘wraps around’’ to a negative number (on my machine -2 14 74 83 64 8). Simi- 21 47 48 36 48 larly, the effect of dividing by zero is undefined, but doing so usually causes abrupt termination of the program. In particular, underflow, overflow, and division by zero do not throw standard excep- tions (§14.10). 6.2.2 Evaluation Order [expr.evaluation] The order of evaluation of subexpressions within an expression is undefined. In particular, you cannot assume that the expression is evaluated left to right. For example: i nt x = f 2)+g 3); // undefined whether f() or g() is called first in t f(2 g(3
    133. Section 6.2.2 Evaluation Order 123 Better code can be generated in the absence of restrictions on expression evaluation order. How- ever, the absence of restrictions on evaluation order can lead to undefined results. For example, i nt i = 1 in t 1; v i] = i v[i i++; // undefined result may be evaluated as either v 1]=1 or v 2]=1 or may cause some even stranger behavior. Com- v[1 1 v[2 1 pilers can warn about such ambiguities. Unfortunately, most do not. The operators , (comma), && (logical and), and || (logical or) guarantee that their left-hand operand is evaluated before their right-hand operand. For example, b a=2 a+1 assigns 3 to b b=(a 2,a 1) b. Examples of the use of || and && can be found in §6.2.3. For built-in types, the second operand of && is evaluated only if its first operand is t ru e, and the second operand of || is evaluated only if its tr ue first operand is f al se this is sometimes called short-circuit evaluation. Note that the sequencing fa ls e; operator , (comma) is logically different from the comma used to separate arguments in a function call. Consider: f 1(v i],i f1 v[i i++); // two arguments f 2( (v i],i f2 v[i i++) ); // one argument The call of f 1 has two arguments, v i] and i f1 v[i i++, and the order of evaluation of the argument expressions is undefined. Order dependence of argument expressions is very poor style and has undefined behavior. The call of f 2 has one argument, the comma expression (v i],i f2 v[i i++), which is equivalent to i i++. Parentheses can be used to force grouping. For example, a b/c means (a b)/c so parenthe- a*b c a*b c ses must be used to get a b/c a b/c may be evaluated as (a b)/c only if the user cannot a*(b c); a*(b c) a*b c tell the difference. In particular, for many floating-point computations a b/c and (a b)/c are a*(b c) a*b c significantly different, so a compiler will evaluate such expressions exactly as written. 6.2.3 Operator Precedence [expr.precedence] Precedence levels and associativity rules reflect the most common usage. For example, i f (i 0 || m ax i) // ... if i<=0 ma x<i means ‘‘if i is less than or equal to 0 or if m ax is less than i That is, it is equivalent to ma x i.’’ i f ( (i 0) || (m ax i) ) // ... if i<=0 ma x<i and not the legal but nonsensical i f (i <= (0 ma x) < i // ... if i 0||m ax i) However, parentheses should be used whenever a programmer is in doubt about those rules. Use of parentheses becomes more common as the subexpressions become more complicated, but compli- cated subexpressions are a source of errors. Therefore, if you start feeling the need for parentheses, you might consider breaking up the expression by using an extra variable. There are cases when the operator precedence does not result in the ‘‘obvious’’ interpretation. For example: i f (i ma sk == 0 if i&m as k 0) // oops! == expression as operand for &
    134. 124 Expressions and Statements Chapter 6 This does not apply a mask to i and then test if the result is zero. Because == has higher prece- dence than &, the expression is interpreted as i ma sk 0). Fortunately, it is easy enough for a i&(m as k==0 compiler to warn about most such mistakes. In this case, parentheses are important: i f ((i ma sk == 0 // ... if i&m as k) 0) It is worth noting that the following does not work the way a mathematician might expect: i f (0 <= x <= 9 9) // ... if 0 99 This is legal, but it is interpreted as (0 x)<=9 9, where the result of the first comparison is either 0<=x 99 t ru e or f al se This Boolean value is then implicitly converted to 1 or 0 which is then compared to tr ue fa ls e. 0, 9 9, yielding t ru e. To test whether x is in the range 0 99 we might use: 99 tr ue 0..9 9, i f (0 x && x 99 // ... if 0<=x x<=9 9) A common mistake for novices is to use = (assignment) instead of == (equals) in a condition: i f (a = 7 // oops! constant assignment in condition if a 7) This is natural because = means ‘‘equals’’ in many languages. Again, it is easy for a compiler to warn about most such mistakes – and many do. 6.2.4 Bitwise Logical Operators [expr.logical] The bitwise logical operators &, |, ^, ~, >>, and << are applied to objects of integer types – that is, b oo l, c ha r, s ho rt i nt l on g, and their u ns ig ne d counterparts. The results are also integers. bo ol ch ar sh or t, in t, lo ng un si gn ed A typical use of bitwise logical operators is to implement the notion of a small set (a bit vector). In this case, each bit of an unsigned integer represents one member of the set, and the number of bits limits the number of members. The binary operator & is interpreted as intersection, | as union, ^ as symmetric difference, and ~ as complement. An enumeration can be used to name the mem- bers of such a set. Here is a small example borrowed from an implementation of o st re am os tr ea m: e nu m i os _b as e::i os ta te { en um io s_ ba se io st at e g oo db it 0, e of bi t=1 f ai lb it 2, b ad bi t=4 go od bi t=0 eo fb it 1, fa il bi t=2 ba db it 4 }; The implementation of a stream can set and test its state like this: s ta te = g oo db it st at e go od bi t; // ... i f (s ta te ba db it fa il bi t)) // stream no good if st at e&(b ad bi t|f ai lb it The extra parentheses are necessary because & has higher precedence than |. A function that reaches the end of input might report it like this: s ta te |= e of bi t; st at e eo fb it The |= operator is used to add to the state. A simple assignment, s ta te eo fb it would have cleared st at e=e of bi t, all other bits. These stream state flags are observable from outside the stream implementation. For example, we could see how the states of two streams differ like this:
    135. Section 6.2.4 Bitwise Logical Operators 125 i nt d if f = c in rd st at e()^c ou t.r ds ta te ; in t di ff ci n.r ds ta te co ut rd st at e() // rdstate() returns the state Computing differences of stream states is not very common. For other similar types, computing differences is essential. For example, consider comparing a bit vector that represents the set of interrupts being handled with another that represents the set of interrupts waiting to be handled. Please note that this bit fiddling is taken from the implementation of iostreams rather than from the user interface. Convenient bit manipulation can be very important, but for reliability, maintain- ability, portability, etc., it should be kept at low levels of a system. For more general notions of a set, see the standard library s et (§17.4.3), b it se t (§17.5.3), and v ec to r<b oo l> (§16.3.11). se t bi ts et ve ct or bo ol Using fields (§C.8.1) is really a convenient shorthand for shifting and masking to extract bit fields from a word. This can, of course, also be done using the bitwise logical operators. For example, one could extract the middle 16 bits of a 32-bit l on g like this: lo ng u ns ig ne d s ho rt m id dl e(l on g a { r et ur n (a 8)&0 xf ff f; } un si gn ed sh or t mi dd le lo ng a) re tu rn a>>8 0x ff ff Do not confuse the bitwise logical operators with the logical operators: &&, ||, and ! . The latter return either t ru e or f al se and they are primarily useful for writing the test in an i f, w hi le or f or tr ue fa ls e, if wh il e, fo r statement (§6.3.2, §6.3.3). For example, !0 (not zero) is the value t ru e, whereas ~0 (complement 0 tr ue 0 of zero) is the bit pattern all-ones, which in two’s complement representation is the value -1 1. 6.2.5 Increment and Decrement [expr.incr] The ++ operator is used to express incrementing directly, rather than expressing it indirectly using a combination of an addition and an assignment. By definition, ++l va lu e means l va lu e+=1 which lv al ue lv al ue 1, again means l va lu e=l va lu e+1 provided l va lu e has no side effects. The expression denoting the lv al ue lv al ue 1 lv al ue object to be incremented is evaluated once (only). Decrementing is similarly expressed by the -- operator. The operators ++ and -- can be used as both prefix and postfix operators. The value of ++x is the new (that is, incremented) value of x For example, y x x. y=++x is equivalent to y x+=1 x y=(x 1). The value of x x++, however, is the old value of x For example, y x++ is equivalent to x. y=x y t=x x+=1 t), where t is a variable of the same type as x y=(t x,x 1,t x. Like addition and subtraction of pointers, ++ and -- on pointers operate in terms of elements of the array into which the pointer points; p makes p point to the next element (§5.3.1). p++ The increment operators are particularly useful for incrementing and decrementing variables in loops. For example, one can copy a zero-terminated string like this: v oi d c py ch ar p c on st c ha r* q vo id cp y(c ha r* p, co ns t ch ar q) { w hi le (*p = *q wh il e p++ q++) ; } Like C, C++ is both loved and hated for enabling such terse, expression-oriented coding. Because w hi le (*p = *q wh il e p++ q++) ; is more than a little obscure to non-C programmers and because the style of coding is not uncom- mon in C and C++, it is worth examining more closely. Consider first a more traditional way of copying an array of characters:
    136. 126 Expressions and Statements Chapter 6 i nt l en gt h = s tr le n(q ; in t le ng th st rl en q) f or (i nt i = 0 i le ng th i fo r in t 0; i<=l en gt h; i++) p i] = q i]; p[i q[i This is wasteful. The length of a zero-terminated string is found by reading the string looking for the terminating zero. Thus, we read the string twice: once to find its length and once to copy it. So we try this instead: i nt i in t i; f or (i = 0 q i]!=0 ; i fo r i 0; q[i 0 i++) p i] = q i]; p[i q[i p i] = 0 // terminating zero p[i 0; The variable i used for indexing can be eliminated because p and q are pointers: w hi le (*q != 0 { wh il e q 0) p q; *p = *q p p++; // point to next character q q++; // point to next character } *p = 0 p 0; // terminating zero Because the post-increment operation allows us first to use the value and then to increment it, we can rewrite the loop like this: w hi le (*q != 0 { wh il e q 0) p++ = *q q++; *p } *p = 0 // terminating zero p 0; The value of *p = *q is *q We can therefore rewrite the example like this: p++ q++ q. w hi le ((*p wh il e p++ = *q q++) != 0 { } 0) In this case, we don’t notice that *q is zero until we already have copied it into *p and incremented q p p Consequently, we can eliminate the final assignment of the terminating zero. Finally, we can p. reduce the example further by observing that we don’t need the empty block and that the ‘‘!= 0 is 0’’ redundant because the result of a pointer or integral condition is always compared to zero anyway. Thus, we get the version we set out to discover: w hi le (*p wh il e p++ = *q q++) ; Is this version less readable than the previous versions? Not to an experienced C or C++ program- mer. Is this version more efficient in time or space than the previous versions? Except for the first version that called s tr le n(), not really. Which version is the most efficient will vary among st rl en machine architectures and among compilers. The most efficient way of copying a zero-terminated character string for your particular machine ought to be the standard string copy function: // from <string.h> c ha r* s tr cp y(c ha r*, c on st c ha r*); ch ar st rc py ch ar co ns t ch ar For more general copying, the standard c op y algorithm (§2.7.2, §18.6.1) can be used. Whenever co py possible, use standard library facilities in preference to fiddling with pointers and bytes. Standard library functions may be inlined (§7.1.1) or even implemented using specialized machine
    137. Section 6.2.5 Increment and Decrement 127 instructions. Therefore, you should measure carefully before believing that some piece of hand- crafted code outperforms library functions. 6.2.6 Free Store [expr.free] A named object has its lifetime determined by its scope (§4.9.4). However, it is often useful to cre- ate an object that exists independently of the scope in which it was created. In particular, it is com- mon to create objects that can be used after returning from the function in which they were created. The operator n ew creates such objects, and the operator d el et e can be used to destroy them. ne w de le te Objects allocated by n ew are said to be ‘‘on the free store’’ (also, to be ‘‘heap objects,’’ or ‘‘allo- ne w cated in dynamic memory’’). Consider how we might write a compiler in the style used for the desk calculator (§6.1). The syntax analysis functions might build a tree of the expressions for use by the code generator: s tr uc t E no de { st ru ct En od e T ok en _v al ue o pe r; To ke n_ va lu e op er E no de l ef t; En od e* le ft E no de r ig ht En od e* ri gh t; // ... }; E no de e xp r(b oo l g et En od e* ex pr bo ol ge t) { E no de l ef t = t er m(g et ; En od e* le ft te rm ge t) f or (;;) fo r sw it ch cu rr _t ok s wi tc h(c ur r_ to k) { c as e P LU S: ca se PL US c as e M IN US ca se MI NU S: E no de n = n ew E no de En od e* ne w En od e; // create an Enode on free store { n->o pe r cu rr _t ok n op er = c ur r_ to k; n le ft = l ef t; n->l ef t le ft n ri gh t = t er m(t ru e); n->r ig ht te rm tr ue l ef t = n le ft n; b re ak br ea k; } d ef au lt de fa ul t: r et ur n l ef t; re tu rn le ft // return node } } A code generator would then use the resulting nodes and delete them: v oi d g en er at e(E no de n vo id ge ne ra te En od e* n) { s wi tc h (n op er { sw it ch n->o pe r) c as e P LU S: ca se PL US // ... d el et e n // delete an Enode from the free store de le te n; } }
    138. 128 Expressions and Statements Chapter 6 An object created by n ew exists until it is explicitly destroyed by d el et e. Then, the space it occu- ne w de le te pied can be reused by n ew A C++ implementation does not guarantee the presence of a ‘‘garbage ne w. collector’’ that looks out for unreferenced objects and makes them available to n ew for reuse. Con- ne w sequently, I will assume that objects created by n ew are manually freed using d el et e. If a garbage ne w de le te collector is present, the d el et es can be omitted in most cases (§C.9.1). de le te The d el et e operator may be applied only to a pointer returned by n ew or to zero. Applying de le te ne w d el et e to zero has no effect. de le te More specialized versions of operator n ew can also be defined (§15.6). ne w 6.2.6.1 Arrays [expr.array] Arrays of objects can also be created using n ew For example: ne w. ch ar sa ve _s tr in g(c on st ch ar p) c ha r* s av e_ st ri ng co ns t c ha r* p { c ha r* s = n ew c ha r[s tr le n(p 1]; ch ar ne w ch ar st rl en p)+1 s tr cp y(s p); st rc py s,p // copy from p to s r et ur n s re tu rn s; } i nt m ai n(i nt a rg c, c ha r* a rg v[]) in t ma in in t ar gc ch ar ar gv { i f (a rg c < 2 e xi t(1 ; if ar gc 2) ex it 1) sa ve _s tr in g(a rg v[1 c ha r* p = s av e_ st ri ng ar gv 1]); ch ar // ... d el et e[] p de le te p; } The ‘‘plain’’ operator d el et e is used to delete individual objects; d el et e[] is used to delete arrays. de le te de le te To deallocate space allocated by n ew d el et e and d el et e[] must be able to determine the size of ne w, de le te de le te the object allocated. This implies that an object allocated using the standard implementation of n ew will occupy slightly more space than a static object. Typically, one word is used to hold the ne w object’s size. Note that a v ec to r (§3.7.1, §16.3) is a proper object and can therefore be allocated and deallo- ve ct or cated using plain n ew and d el et e. For example: ne w de le te v oi d f in t n vo id f(i nt n) { v ec to r<i nt ve ct or in t>* p = n ew v ec to r<i nt n); ne w ve ct or in t>(n // individual object i nt q = n ew i nt n]; in t* ne w in t[n // array // ... d el et e p de le te p; d el et e[] q de le te q; }
    139. Section 6.2.6.2 Memory Exhaustion 129 6.2.6.2 Memory Exhaustion [expr.exhaust] The free store operators n ew d el et e, n ew ne w, de le te ne w[], and d el et e[] are implemented using functions: de le te v oi d* o pe ra to r n ew si ze _t ; vo id op er at or ne w(s iz e_ t) // space for individual object v oi d o pe ra to r d el et e(v oi d*); vo id op er at or de le te vo id si ze _t v oi d* o pe ra to r n ew vo id op er at or ne w[](s iz e_ t); // space for array v oi d o pe ra to r d el et e[](v oi d*); vo id op er at or de le te vo id When operator n ew needs to allocate space for an object, it calls o pe ra to r n ew to allocate a suit- ne w op er at or ne w() able number of bytes. Similarly, when operator n ew needs to allocate space for an array, it calls ne w o pe ra to r n ew op er at or ne w[](). The standard implementations of o pe ra to r n ew op er at or ne w() and o pe ra to r n ew op er at or ne w[]() do not initialize the memory returned. What happens when n ew can find no store to allocate? By default, the allocator throws a ne w b ad _a ll oc exception. For example: ba d_ al lo c v oi d f vo id f() { t ry { tr y f or fo r(;;) n ew c ha r[1 00 00 ; ne w ch ar 10 00 0] } ca tc h(b ad _a ll oc c at ch ba d_ al lo c) { c er r << \"M em or y e xh au st ed \\n ce rr Me mo ry ex ha us te d!\\ n\"; } } However much memory we have available, this will eventually invoke the b ad _a ll oc handler. ba d_ al lo c We can specify what n ew should do upon memory exhaustion. When n ew fails, it first calls a ne w ne w function specified by a call to s et _n ew _h an dl er declared in <n ew if any. For example: se t_ ne w_ ha nd le r() ne w>, v oi d o ut _o f_ st or e() vo id ou t_ of _s to re { c er r << \"o pe ra to r n ew f ai le d: o ut o f s to re \\n ce rr op er at or ne w fa il ed ou t of st or e\\ n\"; t hr ow b ad _a ll oc ; th ro w ba d_ al lo c() } i nt m ai n() in t ma in { s et _n ew _h an dl er ou t_ of _s to re ; // make out_of_store the new_handler se t_ ne w_ ha nd le r(o ut _o f_ st or e) f or (;;) n ew c ha r[1 00 00 ; fo r ne w ch ar 10 00 0] c ou t << \"d on e\\ n\"; co ut do ne \\n } This will never get to write d on e. Instead, it will write do ne o pe ra to r n ew f ai le d: o ut o f s to re op er at or ne w fa il ed ou t of st or e See §14.4.5 for a plausible implementation of an o pe ra to r n ew op er at or ne w() that checks to see if there is a new handler to call and that throws b ad _a ll oc if not. A n ew _h an dl er might do something more ba d_ al lo c ne w_ ha nd le r clever than simply terminating the program. If you know how n ew and d el et e work – for example, ne w de le te
    140. 130 Expressions and Statements Chapter 6 because you provided your own o pe ra to r n ew op er at or ne w() and o pe ra to r d el et e() – the handler might op er at or de le te attempt to find some memory for n ew to return. In other words, a user might provide a garbage ne w collector, thus rendering the use of d el et e optional. Doing this is most definitely not a task for a de le te beginner, though. For almost everybody who needs an automatic garbage collector, the right thing to do is to acquire one that has already been written and tested (§C.9.1). By providing a n ew _h an dl er we take care of the check for memory exhaustion for every ordi- ne w_ ha nd le r, nary use of n ew in the program. Two alternative ways of controlling memory allocation exist. We ne w can either provide nonstandard allocation and deallocation functions (§15.6) for the standard uses of n ew or rely on additional allocation information provided by the user (§10.4.11, §19.4.5). ne w 6.2.7 Explicit Type Conversion [expr.cast] Sometimes, we have to deal with‘‘raw memory;’’ that is, memory that holds or will hold objects of a type not known to the compiler. For example, a memory allocator may return a v oi d* pointing to vo id newly allocated memory or we might want to state that a given integer value is to be treated as the address of an I/O device: vo id ma ll oc si ze _t v oi d* m al lo c(s iz e_ t); v oi d f vo id f() { st at ic _c as t<i nt i nt p = s ta ti c_ ca st in t*>(m al lo c(1 00 ; in t* ma ll oc 10 0)) // new allocation used as ints I O_ de vi ce d 1 = r ei nt er pr et _c as t<I O_ de vi ce IO _d ev ic e* d1 re in te rp re t_ ca st IO _d ev ic e*>(0 Xf f0 0); 0X ff 00 // device at 0Xff00 // ... } A compiler does not know the type of the object pointed to by the v oi d*. Nor can it know whether vo id the integer 0 Xf f0 0 is a valid address. Consequently, the correctness of the conversions are com- 0X ff 00 pletely in the hands of the programmer. Explicit type conversion, often called casting, is occasion- ally essential. However, traditionally it is seriously overused and a major source of errors. st at ic _c as t The s ta ti c_ ca st operator converts between related types such as one pointer type to another, an enumeration to an integral type, or a floating-point type to an integral type. The r ei nt er pr et _c as t re in te rp re t_ ca st handles conversions between unrelated types such as an integer to a pointer. This distinction st at ic _c as t allows the compiler to apply some minimal type checking for s ta ti c_ ca st and makes it easier for a programmer to find the more dangerous conversions represented as r ei nt er pr et _c as ts. Some re in te rp re t_ ca st s ta ti c_ ca st are portable, but few r ei nt er pr et _c as ts are. Hardly any guarantees are made for st at ic _c as ts re in te rp re t_ ca st r ei nt er pr et _c as t, but generally it produces a value of a new type that has the same bit pattern as its re in te rp re t_ ca st argument. If the target has at least as many bits as the original value, we can r ei nt er pr et _c as t the re in te rp re t_ ca st result back to its original type and use it. The result of a r ei nt er pr et _c as t is guaranteed to be re in te rp re t_ ca st usable only if its result type is the exact type used to define the value involved. Note that r ei nt er pr et _c as t is the kind of conversion that must be used for pointers to functions (§7.7). re in te rp re t_ ca st If you feel tempted to use an explicit type conversion, take the time to consider if it is really necessary. In C++, explicit type conversion is unnecessary in most cases when C needs it (§1.6) and also in many cases in which earlier versions of C++ needed it (§1.6.2, §B.2.3). In many pro- grams, explicit type conversion can be completely avoided; in others, its use can be localized to a few routines. In this book, explicit type conversion is used in realistic situations in §6.2.7, §7.7, §13.5, §15.4, and §25.4.1, only.
    141. Section 6.2.7 Explicit Type Conversion 131 A form of run-time checked conversion, d yn am ic _c as t (§15.4.1), and a cast for removing c on st dy na mi c_ ca st co ns t qualifiers, c on st _c as t (§15.4.2.1), are also provided. co ns t_ ca st From C, C++ inherited the notation (T e, which performs any conversion that can be expressed T)e as a combination of s ta ti c_ ca st r ei nt er pr et _c as ts, and c on st _c as ts to make a value of type T st at ic _c as ts, re in te rp re t_ ca st co ns t_ ca st from the expression e (§B.2.3). This C-style cast is far more dangerous than the named conversion operators because the notation is harder to spot in a large program and the kind of conversion intended by the programmer is not explicit. That is, (T e might be doing a portable conversion T)e between related types, a nonportable conversion between unrelated types, or removing the c on st co ns t modifier from a pointer type. Without knowing the exact types of T and e you cannot tell. e, 6.2.8 Constructors [expr.ctor] The construction of a value of type T from a value e can be expressed by the functional notation T e). For example: T(e v oi d f do ub le d vo id f(d ou bl e d) { i nt i = i nt d); in t in t(d // truncate d c om pl ex z = c om pl ex d); // make a complex from d co mp le x co mp le x(d // ... } The T e) construct is sometimes referred to as a function-style cast. For a built-in type T T e) is T(e T, T(e st at ic _c as t<T e). equivalent to s ta ti c_ ca st T>(e Unfortunately, this implies that the use of T e) is not always T(e safe. For arithmetic types, values can be truncated and even explicit conversion of a longer integer type to a shorter (such as l on g to c ha r) can result in undefined behavior. I try to use the notation lo ng ch ar exclusively where the construction of a value is well-defined; that is, for narrowing arithmetic con- versions (§C.6), for conversion from integers to enumerations (§4.8), and the construction of objects of user-defined types (§2.5.2, §10.2.3). Pointer conversions cannot be expressed directly using the T e) notation. For example, T(e c ha r*(2 is a syntax error. Unfortunately, the protection that the constructor notation provides ch ar 2) against such dangerous conversions can be circumvented by using t yp ed ef names (§4.9.7) for ty pe de f pointer types. The constructor notation T is used to express the default value of type T For example: T() T. v oi d f do ub le d vo id f(d ou bl e d) { i nt j = i nt ; in t in t() // default int value c om pl ex z = c om pl ex ; co mp le x co mp le x() // default complex value // ... } The value of an explicit use of the constructor for a built-in type is 0 converted to that type (§4.9.5). Thus, i nt in t() is another way of writing 0 For a user-defined type T T 0. T, T() is defined by the default constructor (§10.4.2), if any. The use of the constructor notation for built-in types is particularly important when writing tem- plates. Then, the programmer does not know whether a template parameter will refer to a built-in type or a user-defined type (§16.3.4, §17.4.1.2).
    142. 132 Expressions and Statements Chapter 6 6.3 Statement Summary [expr.stmts] Here are a summary and some examples of C++ statements: _ ______________________________________________________________  ______________________________________________________________ _ _ ______________________________________________________________ Statement Syntax   statement:    declaration   { statement-listopt }   t ry { statement-listopt } handler-list tr y   expressionopt ;       i f ( condition ) statement if   i f ( condition ) statement e ls e statement if el se   s wi tc h ( condition ) statement sw it ch     w hi le ( condition ) statement wh il e     d o statement w hi le ( expression ) ; do wh il e  f or ( for-init-statement conditionopt ; expressionopt ) statement  fo r     c as e constant-expression : statement ca se   d ef au lt : statement de fa ul t     b re ak ; br ea k   c on ti nu e ; co nt in ue     r et ur n expressionopt ; re tu rn       g ot o identifier ; go to   identifier : statement    statement-list:    statement statement-listopt      condition:    expression   type-specifier declarator = expression      handler-list:    c at ch ( exception-declaration ) { statement-listopt } ca tc h  ______________________________________________________________  _  handler-list handler-listopt Note that a declaration is a statement and that there is no assignment statement or procedure call statement; assignments and function calls are expressions. The statements for handling exceptions, try-blocks, are described in §8.3.1.
    143. Section 6.3.1 Declarations as Statements 133 6.3.1 Declarations as Statements [expr.dcl] A declaration is a statement. Unless a variable is declared s ta ti c, its initializer is executed when- st at ic ever the thread of control passes through the declaration (see also §10.4.8). The reason for allow- ing declarations wherever a statement can be used (and a few other places; §6.3.2.1, §6.3.3.1) is to enable the programmer to minimize the errors caused by uninitialized variables and to allow better locality in code. There is rarely a reason to introduce a variable before there is a value for it to hold. For example: v oi d f ve ct or st ri ng vo id f(v ec to r<s tr in g>& v i nt i c on st c ha r* p v, in t i, co ns t ch ar p) { i f (p 0) r et ur n; if p==0 re tu rn i f (i 0 || v si ze if i<0 v.s iz e()<=i e rr or ba d i nd ex ; i) er ro r(\"b ad in de x\") s tr in g s = v i]; st ri ng v[i i f (s == p { if s p) // ... } // ... } The ability to place declarations after executable code is essential for many constants and for single-assignment styles of programming where a value of an object is not changed after initial- ization. For user-defined types, postponing the definition of a variable until a suitable initializer is available can also lead to better performance. For example, s tr in g s /* ... */ s = \"T he b es t i s t he e ne my o f t he g oo d.\"; st ri ng s; Th e be st is th e en em y of th e go od can easily be much slower than s tr in g s = \"V ol ta ir e\"; st ri ng Vo lt ai re The most common reason to declare a variable without an initializer is that it requires a statement to initialize it. Examples are input variables and arrays. 6.3.2 Selection Statements [expr.select] A value can be tested by either an i f statement or a s wi tc h statement: if sw it ch i f ( condition ) statement if i f ( condition ) statement e ls e statement if el se s wi tc h ( condition ) statement sw it ch The comparison operators == != < <= > >= return the b oo l t ru e if the comparison is true and f al se otherwise. bo ol tr ue fa ls e In an i f statement, the first (or only) statement is executed if the expression is nonzero and the if second statement (if it is specified) is executed otherwise. This implies that any arithmetic or pointer expression can be used as a condition. For example, if x is an integer, then i f (x // ... if x)
    144. 134 Expressions and Statements Chapter 6 means i f (x != 0 // ... if x 0) For a pointer p p, i f (p // ... if p) is a direct statement of the test ‘‘does p point to a valid object,’’ whereas i f (p != 0 // ... if p 0) states the same question indirectly by comparing to a value known not to point to an object. Note that the representation of the pointer 0 is not all-zeros on all machines (§5.1.1). Every compiler I have checked generated the same code for both forms of the test. The logical operators && || ! are most commonly used in conditions. The operators && and || will not evaluate their second argument unless doing so is necessary. For example, i f (p && 1 p->c ou nt // ... if p 1<p co un t) first tests that p is nonzero. It tests 1 p->c ou nt only if p is nonzero. 1<p co un t Some if-statements can conveniently be replaced by conditional-expressions. For example, i f (a <= b if a b) m ax = b ma x b; e ls e el se m ax = a ma x a; is better expressed like this: m ax = (a b) ? b : a ma x a<=b a; The parentheses around the condition are not necessary, but I find the code easier to read when they are used. A switch-statement can alternatively be written as a set of i f-s ta te me nt For example, if st at em en ts. s wi tc h (v al { sw it ch va l) c as e 1 ca se 1: f; f() b re ak br ea k; c as e 2 ca se 2: g; g() b re ak br ea k; d ef au lt de fa ul t: h; h() b re ak br ea k; } could alternatively be expressed as
    145. Section 6.3.2 Selection Statements 135 i f (v al == 1 if va l 1) f; f() e ls e i f (v al == 2 el se if va l 2) g; g() e ls e el se h; h() The meaning is the same, but the first (s wi tc h) version is preferred because the nature of the opera- sw it ch tion (testing a value against a set of constants) is explicit. This makes the s wi tc h statement easier sw it ch to read for nontrivial examples. It can also lead to the generation of better code. Beware that a case of a switch must be terminated somehow unless you want to carry on execut- ing the next case. Consider: s wi tc h (v al { sw it ch va l) // beware c as e 1 ca se 1: c ou t << \"c as e 1 \\n co ut ca se 1\\ n\"; c as e 2 ca se 2: c ou t << \"c as e 2 \\n co ut ca se 2\\ n\"; d ef au lt de fa ul t: c ou t << \"d ef au lt c as e n ot f ou nd \\n co ut de fa ul t: ca se no t fo un d\\ n\"; } Invoked with v al 1, this prints va l==1 c as e 1 ca se c as e 2 ca se d ef au lt c as e n ot f ou nd de fa ul t: ca se no t fo un d to the great surprise of the uninitiated. It is a good idea to comment the (rare) cases in which a fall-through is intentional so that an uncommented fall-through can be assumed to be an error. A b re ak is the most common way of terminating a case, but a r et ur n is often useful (§6.1.1). br ea k re tu rn 6.3.2.1 Declarations in Conditions [expr.cond] To avoid accidental misuse of a variable, it is usually a good idea to introduce the variable into the smallest scope possible. In particular, it is usually best to delay the definition of a local variable until one can give it an initial value. That way, one cannot get into trouble by using the variable before its initial value is assigned. One of the most elegant applications of these two principles is to declare a variable in a condi- tion. Consider: i f (d ou bl e d = p ri m(t ru e)) { if do ub le pr im tr ue l ef t /= d le ft d; b re ak br ea k; } Here, d is declared and initialized and the value of d after initialization is tested as the value of the condition. The scope of d extends from its point of declaration to the end of the statement that the condition controls. For example, had there been an e ls e-branch to the if-statement, d would be in el se scope on both branches.
    146. 136 Expressions and Statements Chapter 6 The obvious and traditional alternative is to declare d before the condition. However, this opens the scope (literally) for the use of d before its initialization or after its intended useful life: d ou bl e d do ub le d; // ... d2 = d d2 d; // oops! // ... i f (d = p ri m(t ru e)) { if d pr im tr ue l ef t /= d le ft d; b re ak br ea k; } // ... d = 2 0; // two unrelated uses of d 2.0 In addition to the logical benefits of declaring variables in conditions, doing so also yields the most compact source code. A declaration in a condition must declare and initialize a single variable or c on st co ns t. 6.3.3 Iteration Statements [expr.loop] A loop can be expressed as a f or w hi le or d o statement: fo r, wh il e, do w hi le ( c on di ti on ) s ta te me nt wh il e co nd it io n st at em en t d o s ta te me nt w hi le ( e xp re ss io n ) ; do st at em en t wh il e ex pr es si on f or ( f or in it st at em en t c on di ti ono ptt ; e xp re ss io no ptt ) s ta te me nt fo r fo r-i ni t-s ta te me nt co nd it io nop ex pr es si on op st at em en t Each of these statements executes a statement (called the controlled statement or the body of the loop) repeatedly until the condition becomes false or the programmer breaks out of the loop some other way. The for-statement is intended for expressing fairly regular loops. The loop variable, the termi- nation condition, and the expression that updates the loop variable can be presented ‘‘up front’’ on a single line. This can greatly increase readability and thereby decrease the frequency of errors. If no initialization is needed, the initializing statement can be empty. If the condition is omitted, the for-statement will loop forever unless the user explicitly exits it by a b re ak r et ur n, g ot o, t hr ow or br ea k, re tu rn go to th ro w, some less obvious way such as a call of e xi t() (§9.4.1.1). If the expression is omitted, we must ex it update some form of loop variable in the body of the loop. If the loop isn’t of the simple ‘‘intro- duce a loop variable, test the condition, update the loop variable’’ variety, it is often better expressed as a while-statement. A for-statement is also useful for expressing a loop without an explicit termination condition: f or fo r(;;) { // ‘‘forever’’ // ... } A while-statement simply executes its controlled statement until its condition becomes f al se I tend fa ls e. to prefer while-statements over for-statements when there isn’t an obvious loop variable or where the update of a loop variable naturally comes in the middle of the loop body. An input loop is an example of a loop where there is no obvious loop variable:
    147. Section 6.3.3 Iteration Statements 137 w hi le ci n>>c h) // ... wh il e(c in ch In my experience, the do-statement is a source of errors and confusion. The reason is that its body is always executed once before the condition is evaluated. However, for the body to work cor- rectly, something very much like the condition must hold even the first time through. More often than I would have guessed, I have found that condition not to hold as expected either when the pro- gram was first written and tested or later after the code preceding it has been modified. I also prefer the condition ‘‘up front where I can see it.’’ Consequently, I tend to avoid do-statements. 6.3.3.1 Declarations in For-Statements [expr.for] A variable can be declared in the initializer part of a for-statement. If that initializer is a declara- tion, the variable (or variables) it introduces is in scope until the end of the for-statement. For example: v oi d f in t v , i nt m ax vo id f(i nt v[] in t ma x) { f or (i nt i = 0 i ma x; i fo r in t 0; i<m ax i++) v i] = i i; v[i i*i } If the final value of an index needs to be known after exit from a f or fo r-loop, the index variable must be declared outside the f or fo r-loop (e.g., §6.3.4). 6.3.4 Goto [expr.goto] C++ possesses the infamous g ot o: go to g ot o identifier ; go to identifier : statement The g ot o has few uses in general high-level programming, but it can be very useful when C++ code go to is generated by a program rather than written directly by a person; for example, g ot os can be used go to in a parser generated from a grammar by a parser generator. The g ot o can also be important in the go to rare cases in which optimal efficiency is essential, for example, in the inner loop of some real-time application. One of the few sensible uses of g ot o in ordinary code is to break out from a nested loop or go to switch-statement (a b re ak breaks out of only the innermost enclosing loop or switch-statement). br ea k For example: v oi d f vo id f() { i nt i in t i; i nt j in t j;
    148. 138 Expressions and Statements Chapter 6 f or (i = 0 i n; i fo r i 0; i<n i++) f or (j = 0 j m; j fo r j 0; j<m j++) i f (n m[i j] == a g ot o f ou nd if nm i][j a) go to fo un d; // not found // ... f ou nd fo un d: // nm[i][j] == a } There is also a c on ti nu e statement that, in effect, goes to the end of a loop statement, as explained co nt in ue in §6.1.5. 6.4 Comments and Indentation [expr.comment] Judicious use of comments and consistent use of indentation can make the task of reading and understanding a program much more pleasant. Several different consistent styles of indentation are in use. I see no fundamental reason to prefer one over another (although, like most programmers, I have my preferences, and this book reflects them). The same applies to styles of comments. Comments can be misused in ways that seriously affect the readability of a program. The com- piler does not understand the contents of a comment, so it has no way of ensuring that a comment [1] is meaningful, [2] describes the program, and [3] is up to date. Most programs contain comments that are incomprehensible, ambiguous, and just plain wrong. Bad comments can be worse than no comments. If something can be stated in the language itself, it should be, and not just mentioned in a com- ment. This remark is aimed at comments such as these: // variable \"v\" must be initialized // variable \"v\" must be used only by function \"f()\" // call function \"init()\" before calling any other function in this file // call function \"cleanup()\" at the end of your program // don’t use function \"weird()\" // function \"f()\" takes two arguments Such comments can often be rendered unnecessary by proper use of C++. For example, one might utilize the linkage rules (§9.2) and the visibility, initialization, and cleanup rules for classes (see §10.4.1) to make the preceding examples redundant. Once something has been stated clearly in the language, it should not be mentioned a second time in a comment. For example: a = b c; // a becomes b+c b+c c ou nt co un t++; // increment the counter Such comments are worse than simply redundant. They increase the amount of text the reader has to look at, they often obscure the structure of the program, and they may be wrong. Note, however,
    149. Section 6.4 Comments and Indentation 139 that such comments are used extensively for teaching purposes in programming language textbooks such as this. This is one of the many ways a program in a textbook differs from a real program. My preference is for: [1] A comment for each source file stating what the declarations in it have in common, refer- ences to manuals, general hints for maintenance, etc. [2] A comment for each class, template, and namespace [3] A comment for each nontrivial function stating its purpose, the algorithm used (unless it is obvious), and maybe something about the assumptions it makes about its environment [4] A comment for each global and namespace variable and constant [5] A few comments where the code is nonobvious and/or nonportable [6] Very little else For example: tbl.c: Implementation of the symbol table. // /* Gaussian elimination with partial pivoting. See Ralston: \"A first course ...\" pg 411. */ swap() assumes the stack layout of an SGI R6000. // /*********************************** Copyright (c) 1997 AT&T, Inc. All rights reserved ************************************/ A well-chosen and well-written set of comments is an essential part of a good program. Writing good comments can be as difficult as writing the program itself. It is an art well worth cultivating. Note also that if // comments are used exclusively in a function, then any part of that function can be commented out using /* */ style comments, and vice versa. 6.5 Advice [expr.advice] [1] Prefer the standard library to other libraries and to ‘‘handcrafted code;’’ §6.1.8. [2] Avoid complicated expressions; §6.2.3. [3] If in doubt about operator precedence, parenthesize; §6.2.3. [4] Avoid explicit type conversion (casts);