C Without Fear

Transcription

C Without FearSecond Edition

This page intentionally left blank

C Without FearSecond EditionA Beginner’s Guide ThatMakes You Feel SmartBrian OverlandUpper Saddle River, NJ Boston Indianapolis San FranciscoNew York Toronto Montreal London Munich Paris MadridCapetown Sydney Tokyo Singapore Mexico City

Many of the designations used by manufacturers and sellers to distinguish their products areclaimed as trademarks. Where those designations appear in this book, and the publisher was awareof a trademark claim, the designations have been printed with initial capital letters or in all capitals.The author and publisher have taken care in the preparation of this book, but make no expressedor implied warranty of any kind and assume no responsibility for errors or omissions. No liabilityis assumed for incidental or consequential damages in connection with or arising out of the use ofthe information or programs contained herein.The publisher offers excellent discounts on this book when ordered in quantity for bulk purchasesor special sales, which may include electronic versions and/or custom covers and content particular to your business, training goals, marketing focus, and branding interests. For more information, please contact:U.S. Corporate and Government Sales(800) 382-3419corpsales@pearsontechgroup.comFor sales outside the United States please contact:International Salesinternational@pearson.comVisit us on the Web: informit.com/phLibrary of Congress Cataloging-in-Publication DataOverland, Brian R.C without fear : a beginner's guide that makes you feel smart /Brian Overland.—2nd ed.p. cm.Includes index.ISBN 978-0-13-267326-6 (pbk. : alk. paper)1. C (Computer program language) I. Title.QA76.73.C153O838 2011005.13'3—dc222011004218Copyright 2011 Pearson Education, Inc.All rights reserved. Printed in the United States of America. This publication is protected by copyright, and permission must be obtained from the publisher prior to any prohibited reproduction,storage in a retrieval system, or transmission in any form or by any means, electronic, mechanical,photocopying, recording, or likewise. For information regarding permissions, write to:Pearson Education, Inc.Rights and Contracts Department501 Boylston Street, Suite 900Boston, MA 02116Fax: (617) 671-3447ISBN-13: 978-0-13-267326-6ISBN-10:0-13-267326-6Text printed in the United States on recycled paper at Edwards Brothers in Ann Arbor, Michigan.Third printing, August 2012

For Colin

This page intentionally left blank

ContentsChapter 1PrefacexxiiiAbout This Book: How It’s DifferentOnward to the Second Edition“Where Do I Begin?”Icons, Icons, Who’s Got the Icons?What Is Not Covered?Getting Started with C : A Free CompilerA Final Note: Have out the AuthorxxixxxxiYour First C Programs1Thinking Like a ProgrammerComputers Do Only What You Tell ThemDetermine What the Program Will DoWrite the Equivalent C StatementsInterlude How “Smart” Are Computers, Really?Some Nerdy Definitions—A ReviewWhat’s Different About C ?Building a C ProgramEnter the Program StatementsBuild the Program (Compile and Link)1112447888vii

viiiChapter 2ContentsTest the ProgramRevise as NeededInstalling Your Own C CompilerExample 1.1. Print a MessageIf You’re Using the Dev-C EnvironmentIf You’re Using Microsoft Visual StudioHow It WorksExercisesInterlude What about the #include and using?Advancing to the Next Print LineExample 1.2. Print Multiple LinesHow It WorksExercisesInterlude What Is a String?Storing Data: C VariablesIntroduction to Data TypesInterlude Why Double Precision, Not Single?Example 1.3. Convert TemperaturesHow It WorksOptimizing the ProgramExercisesA Word about Variable Names and KeywordsExerciseChapter 1 930Decisions, Decisions33But First, a Few Words about Data TypesDecision Making in ProgramsInterlude What about Artificial Intelligence (AI)?if and if-elseInterlude Why Two Operators ( and )?Example 2.1. Odd or Even?How It WorksOptimizing the CodeExerciseIntroducing LoopsInterlude Infinite LoopinessExample 2.2. Print 1 to N333435353839404242434646

ContentsChapter 3ixHow It WorksOptimizing the ProgramExercisesTrue and False in C Interlude The bool Data TypeThe Increment Operator ( )Statements vs. ExpressionsIntroducing Boolean (Short-Circuit) LogicInterlude What Is “true”?Example 2.3. Testing a Person’s AgeHow It WorksExerciseIntroducing the Math LibraryExample 2.4. Prime-Number TestHow It WorksOptimizing the ProgramExerciseExample 2.5. The Subtraction Game (NIM)How It WorksExercisesChapter 2 he Handy, All-Purpose “for” Statement67Loops Used for CountingIntroducing the “for” LoopA Wealth of ExamplesInterlude Does “for” Always Behave Like “while”?Example 3.1. Printing 1 to N with “for”How It WorksExercisesCompound Statements (Blocks) with “for”Declaring Loop Variables on the FlyExample 3.2. Prime-Number Test with “for”How It WorksExerciseComparative Languages 101: The Basic “For” StatementChapter 3 Summary6768707172737374747577797980

xContentsChapter 4Functions: Many Are CalledChapter 583The Concept of FunctionThe Basics of Using FunctionsStep 1: Declare (Prototype) the FunctionStep 2: Define the FunctionStep 3: Call the FunctionExample 4.1. The avg() FunctionHow It WorksFunction Call a Function!ExercisesExample 4.2. Prime-Number FunctionHow It WorksExercisesLocal and Global VariablesInterlude Why Global Variables at All?Recursive FunctionsExample 4.3. Prime FactorizationHow It WorksInterlude Interlude for Math JunkiesExercisesExample 4.4. Euclid’s Algorithm for GCFHow It WorksInterlude Who Was Euclid?ExercisesInterlude Interlude for Math Junkies: Rest of the ProofExample 4.5. Beautiful Recursion: Tower of HanoiHow It WorksExercisesExample 4.6. Random-Number GeneratorHow It WorksExercisesGames and More GamesChapter 4 103104105105106109110110111113113115Arrays: All in a Row.117A First Look at C ArraysInitializing Arrays117119

ContentsChapter 6xiZero-Based IndexingInterlude Why Use Zero-Based Indexes?Example 5.1. Print Out ElementsHow It WorksExercisesExample 5.2. How Random Is Random?How It WorksExercisesStrings and Arrays of StringsExample 5.3. Card Dealer #1How It WorksExerciseExample 5.4. Card Dealer #2How It WorksExerciseExample 5.5. Card Dealer #3How It WorksOptimizing the ProgramExerciseA Word to the Wise2-D Arrays: Into the MatrixChapter 5 35136138140141141142143Pointers: Getting a Handle on Data145What the Heck Is a Pointer, Anyway?The Concept of PointerInterlude What Do Addresses Look Like?Declaring and Using PointersExample 6.1. Print Out AddressesExample 6.2. The double it FunctionHow It WorksExercisesSwap: Another Function Using PointersExample 6.2. Array SorterHow It WorksExercisesPointer Arithmetic145146147148151152153154155156160161161

xiiChapter 7ContentsPointers and Array ProcessingExample 6.3. Zero Out an ArrayHow It WorksWriting More Compact CodeExercisesChapter 6 Summary163165166166167168Strings: Analyzing the Text169Text Storage on the ComputerInterlude How Does the Computer Translate Programs?It Don’t Mean a Thing If It Ain’t Got That StringString-Manipulation FunctionsExample 7.1. Building StringsHow It WorksExercisesInterlude What about Escape Sequences?Reading String InputExample 7.2. Get a NumberHow It WorksExerciseExample 7.3. Convert to UppercaseHow It WorksExercisesIndividual Characters vs. StringsExample 7.4. Breaking Up Input with StrtokHow It WorksExercisesThe New C String TypeInclude String-Class SupportDeclare and Initialize Variables of Type stringWorking with Variables of Type stringInput and OutputExample 7.5. Building Strings with the string TypeHow It WorksExercisesOther Operations on the string TypeChapter 7 85185186188188189189189190191191192193193194

ContentsChapter 8Chapter 9xiiiFiles: Electronic Storage197Introducing File-Stream ObjectsHow to Refer to Disk FilesExample 8.1. Write Text to a FileHow It WorksExercisesExample 8.2. Display a Text FileHow It WorksExercisesText Files vs. “Binary” FilesInterlude Are “Binary Files” Really More Binary?Introducing Binary OperationsExample 8.3. Random-Access WriteHow It WorksExercisesExample 8.4. Random-Access ReadHow It WorksExercisesChapter 8 14216217217Some Advanced Programming Techniques221Command-Line ArgumentsExample 9.1. Display File from Command LineHow It WorksImproving the ProgramInterlude The Virtue of Predefined ConstantsExercisesFunction OverloadingInterlude Overloading and Object OrientationExample 9.2. Printing Different Types of ArraysHow It WorksExerciseThe do-while LoopThe switch-case StatementMultiple ModulesException Handling: I Take Exception to That!Say Hello to 34237237

xivChapter 10Chapter 11ContentsHandling Exceptions: A First AttemptIntroducing try-catch Exception HandlingChapter 9 Summary238238240New Features of C 0x243Overview of C 0x FeaturesThe long long Type (not long long long)Interlude Why a “Natural” Integer?Working with 64-Bit Literals (Constants)Accepting long long InputFormatting long long NumbersExample 10.1. Fibonacci: A 64-Bit ExampleHow It WorksExercisesLocalizing NumbersInterlude Who Was Fibonacci?Range-Based “for” (For Each)Example 10.2. Setting an Array with Range-Based “for”How It WorksExercisesThe auto and decltype KeywordsThe nullptr KeywordStrongly Typed Enumerationsenum Classes in C 0xExtended enum Syntax: Controlling StorageExample 10.3. Rock, Paper, Scissors GameHow It WorksA More Interesting GameExercisesRaw String LiteralsChapter 10 60261262263265266267269271272273273Introducing Classes: The Fraction Class277Object Orientation: Quasi-Intelligent Data TypesInterlude OOP Is It Worth It?Point: A Simple ClassInterlude Interlude for C Programmers: Structures and Classes277278279281

ContentsChapter 12xvPrivate: Members Only (Protecting the Data)Exmple 11.1. Testing the Point ClassHow It WorksExercisesIntroducing the Fraction ClassInline FunctionsFind the Greatest Common FactorFind the Lowest Common DenominatorExample 11.2. Fraction Support FunctionsHow It WorksExercisesExample 11.3. Testing the Fraction ClassHow It WorksInterlude A New Kind of #include?ExerciseExample 11.4. Fraction Arithmetic: add and multHow It WorksExercisesChapter 11 00300304305305Constructors: If You Build It 307Introducing ConstructorsMultiple Constructors (Overloading)C 0x Only: Initializing Members within a ClassThe Default Constructor—and a WarningInterlude Is C Out to Trick You with the Default Constructor?C 0x Only: Delegating ConstructorsC 0x Only: Consistent InitializationExample 12.1. Point Class ConstructorsHow It WorksExercisesExample 12.2. Fraction Class ConstructorsHow It WorksExercisesReference Variables and Arguments (&)The Copy ConstructorInterlude The Copy Constructor and 21323325

xviChapter 13Chapter 14ContentsExample 12.3. Fraction Class Copy ConstructorHow It WorksExercisesA Constructor from String to FractChapter 12 Summary325328329329331Operator Functions: Doing It with Class333Introducing Class Operator FunctionsOperator Functions as Global FunctionsImprove Efficiency with ReferencesExample 13.1. Point Class OperatorsHow It WorksExercisesExample 13.2. Fraction Class OperatorsHow It WorksOptimizing the CodeExercisesWorking with Other TypesThe Class Assignment Function ( )The Test-for-Equality Function ( )A Class “Print” FunctionExample 13.3. The Completed Fraction ClassHow It WorksExercisesC 0x Only: User-Defined LiteralsDefining a Raw-String LiteralDefining a Cooked LiteralChapter 13 52355356357358359360Dynamic Memory and the String Class363Dynamic Memory: The “new” KeywordObjects and “new”Allocating Multiple DataInterlude Dealing with Problems in Memory AllocationExample 14.1. Dynamic Memory in Action363365366368368

ContentsChapter 15Chapter 16xviiHow It WorksExerciseIntroducing Class DestructorsExample 14.2. A Simple String ClassHow It WorksExercises“Deep” Copying and the Copy ConstructorThe “this” KeywordRevisiting the Assignment OperatorWriting a Concatenation FunctionExample 14.3. The Complete String ClassHow It WorksExercisesChapter 14 wo Complete OOP Examples389Introducing Linked ListsNode DesignImplementing a Simple Linked ListAn Alphabetical ListExample 15.1. Names in Alpha OrderHow It WorksDealing with Memory LeaksC Only: Using Smart Pointers to Clean UpInterlude Recursion vs. Iteration ComparedExercisesTower of Hanoi, AnimatedMystack Class DesignUsing the Mystack ClassExample 15.2. Animated TowerHow It WorksExercisesChapter 15 08410411Easy Programming with STL413Introducing the List TemplateInterlude Writing Templates in C 413414

xviiiChapter 17Chapter 18ContentsCreating and Using a List ClassCreating and Using IteratorsC 0x Only: For EachInterlude Pointers vs. IteratorsExample 16.1. STL Ordered ListHow It WorksA Continually Sorted ListExercisesDesigning an RPN CalculatorInterlude A Brief History of Polish NotationUsing a Stack for RPNIntroducing the Generalized STL Stack ClassExample 16.2. Reverse Polish CalculatorHow It WorksExercisesCorrect Interpretation of Angle BracketsChapter 16 31432432Inheritance: What a Legacy435How to SubclassInterlude Why “public” Base Classes?Example 17.1. The FloatFraction ClassHow It WorksExercisesProblems with the FloatFraction ClassC Only: Inheriting Base-Class ConstructorsExample 17.2. The Completed FloatFraction ClassHow It WorksExercisesProtected MembersObject ContainmentSafe Inheritance Through Class HierarchiesChapter 17 olymorphism: Object Independence453A Different Approach to the FloatFraction ClassVirtual Functions to the Rescue!453454

ContentsInterludeAppendix AAppendix BxixWhat Is the Virtual Penalty?Example 18.1. The Revised FloatFraction ClassHow It WorksExerciseC Only: Requiring Explicit Overrides“Pure Virtual” and Other Abstract MattersAbstract Classes and InterfacesObject Orientation and I/Ocout Is Endlessly ExtensibleBut cout Is Not PolymorphicExample 18.2. True Polymorphism: The Printable ClassHow It WorksExerciseA Final Word (or Two)A Final, Final WordChapter 18 72472Operators475The Scope (::) OperatorThe sizeof OperatorOld and New Style Type CastsInteger vs. Floating-Point DivisionBitwise Operators (&, , , , , and )Conditional OperatorAssignment OperatorsJoin (,) Operator478478479480480481482482Data Types483Precision of Data TypesData Types of Numeric LiteralsString Literals and Escape SequencesTwo’s Complement Format for Signed Integers484485486487

xxContentsAppendix CSyntax Summary491Basic Expression SyntaxBasic Statement SyntaxControl Structures and Branch StatementsThe if-else StatementThe while StatementThe do-while StatementThe for StatementThe switch-case StatementThe break StatementThe continue StatementThe goto StatementThe return StatementThe throw StatementVariable DeclarationsFunction DeclarationsClass DeclarationsEnum 7498500502503Preprocessor Directives505The #define DirectiveThe ## Operator (Concatenation)The defined FunctionThe #elif DirectiveThe #endif DirectiveThe #error DirectiveThe #if DirectiveThe #ifdef DirectiveThe #ifndef DirectiveThe #include DirectiveThe #line DirectiveThe #undef DirectivePredefined pendix D

ContentsxxiAppendix EASCII Codes513Appendix FStandard Library Functions517String (C-String) FunctionsData-Conversion FunctionsSingle-Character FunctionsMath FunctionsRandomization FunctionsTime FunctionsFormats for the strftime Function517517517520521521523I/O Stream Objects and Classes525Console Stream ObjectsI/O Stream ManipulatorsInput Stream FunctionsOutput Stream FunctionsFile I/O Functions525526528528529STL Classes and Objects531The STL String ClassThe list TemplateThe stack Template531533535Glossary of Terms537Index553Appendix GAppendix HAppendix I

This page intentionally left blank

PrefaceMany years ago, when I had to learn C overnight to make a living as a programmer (this was before C ), I would have given half my salary to find a mentor, aperson would say, “Here are the potholes in the road.errors that you are sure tomake in learning C. And here’s how to steer around them.” Instead, I had tosweat and groan through every error a person could make.I’m not just talking about programmers who can write or writers who canprogram. Each of those is rare enough. Much rarer still is the person who is programmer, writer, and teacher—someone who will steer you around the elementary gotchas and enthusiastically communicate the “whys” of the language,including why this stuff is not just useful but, in its own way, kind of cool.It’s hard to find such a person. But way back then, I swore this is the person I’dbecome.Later, at Microsoft, I started in tech support and testing and worked my wayinto management. But my most important job (I felt) was explaining new technology. I was sometimes the second or third person in the world to see a new feature of a programming language, and my job was to turn a cryptic spec intoreadable prose for the rest of the universe to understand. I took the goal of “makethis simple” as not just a job but a mission.About This Book: How It’s DifferentWhat’s different about this book is that I’m an advocate for you, the reader. I’mon your side, not that of some committee. I’m aware of all the ways you are “supposed” to program and why they are supposed to be better (and I do discussthose issues), but I’m mostly concerned about telling you what works.This book assumes you know nothing at all about programming—that youbasically know how to turn on a computer and use a mouse. For those of youmore knowledgeable, you’ll want to breeze through the first few chapters.xxiii

xxivPrefaceThe creators of C and C —Dennis Ritchie and Bjarne Stroustrup, respectively—are geniuses, and I’m in awe of what they accomplished. But although Cand C are great languages, there are some features that beginners (and evenrelatively advanced programmers) never find uses for, at least not for the firstfew years. I’m not afraid to tell you that information up front: what language features you can and should ignore. At the same time, I’m also eager to tell youabout the elegant features of C that can save you time and energy.This is a book about practical examples. It’s also a book about having fun! Thegreat majority of examples in this book either are useful and practical or—byusing puzzles and games—are intrinsically entertaining.So, have no fear! I won’t bludgeon you to death with overly used (and highlyabused) terms like data abstraction, which professors love but which foreverremain fuzzy to the rest of us. At the same time, there are some terms—objectorientation and polymorphism—that you will want to know, and I provide concrete, practical contexts for understanding and using them.Onward to the Second EditionThe first edition has sold increasingly well over the years. I believe that’s a testament to the variety of learning paths it supplied: complete examples, exercises,and generous use of conceptual art. The second edition builds on these strengthsin many ways: Coverage of new features in C 0x: This is the new specification for C thatwill be standard by the time you have this book in your hands. Compiler vendorseither have brought their versions of C up to this standard or are in theprocess of doing so. This book covers well over a dozen new features from thisspecification in depth. Examples galore, featuring puzzles and games: By the end of Chapter 2, you’lllearn how to enter a program, barely a page long, that not only is a completegame but even has an optimal strategy for the computer. Just see whether youcan beat it! But this is only the beginning. This edition features puzzles andgames, much more so than the first edition. Generous use of conceptual art: The use of clarifying illustrations to addressabstract points was one of the biggest strengths of the first edition. This editionhas substantially more of these. Even more exercises: These encourage the reader to learn in the best way.bytaking apart an example that works, analyzing it, and figuring out how to modifyit to make it do your own thing.

Prefacexxv No-nonsense syntax diagrams: Programming and playing games is fun, butsometimes you need straightforward information. The syntax diagrams in thisbook, accompanied by loads of examples, clarify exactly how the languageworks, statement by statement and keyword by keyword. Introduction to Standard Template Library (STL): Although I lacked the spaceto do a complete STL manual, this edition (unlike the first) introduces you to thewonders of this exciting feature of C , showing how it can save you time andenergy and enable you to write powerful applications in a remarkably smallspace. Expanded reference: The appendixes in the back are intended as a mini desk reference to use in writing C programs. This edition has significantly expandedthese appendixes. Essays, or “interludes” for the philosophically inclined: Throughout the book, Idetour into areas related to C but that impact the larger world, such as computer science, history of programming, mathematics, philosophy, and artificialintelligence. But these essays are set aside as sidebars so as not to interfere withthe flow of the subject. You can read them at your leisure.“Where Do I Begin?”As I mentioned, this book assumes you know nothing about programming. Ifyou can turn on a computer and use a menu system, keyboard, and mouse, youcan begin on page 1. If you already have some familiarity with programming,you’ll want to go through the first two or three chapters quickly.If you already know a lot about C or C and are mainly interested in the newfeatures of C 0x, you may want to go straight to Chapter 10, “New Features ofC 0x.”And if you know C and are now starting to learn about object orientationwith the C language, you may want to start with Chapter 11, “IntroducingClasses: The Fraction Class.”Icons, Icons, Who’s Got the Icons?Building on the helpful icons used in the first edition, this edition provides evenmore—as signposts on the pages to help you find what you need. Be sure to lookfor these symbols.

xxviPrefaceThese sections take apart program examples and explain, line by line, how andwhy the examples work. You don’t have to wade through long programmingexamples. I do that for you! (Or rather, we go through the examples together.)seAfter each full programming example, I provide at least one exercise, and usuallyseveral, that builds on the example in some way. These encourage you to alterand extend the programming code you’ve just seen. This is the best way to learn.The answers can be found on the book’s Web site (www.informit.com/title/9780132673266).ExerciHow It WorksOptimizingVariationsThese sections develop an example by showing how it can be improved, madeshorter, or made more efficient.As with “Optimizing,” these sections take the example in new directions, helpingyou learn by showing how the example can be varied or modified to do otherthings.KeywordThis icon indicates a place where a keyword of the language is introduced and itsusage clearly defined.C 0x 䊳 This icon is used to indicate sections that apply only to versions of C compliant with the new C 0x specification. Depending on the version of C you have, either these sections will apply to you or they won’t. If your version isnot C 0x-compliant, you’ll generally want to skip these sections.What Is Not Covered?Relatively little, as it turns out. The two features not covered at all are bit fieldsand unions. Although these features are useful for some people, their applicationtends to be highly specialized—limited to a few special situations—and not particularly useful to people first learning the language. Of course, I encourage youto learn about them on your own later.Another area in which I defer to other books is the topic of writing your owntemplate classes, which I touch on just briefly in Chapter 16. Without a doubt,the ability to write new template classes is one of the most amazing features ofstate-of-the-art C , but it is a very advanced and complex topic. For me tocover it adequately and exhaustively could easily have taken another 400 or 500pages!

PrefacexxviiFortunately, although templates and the Standard Template Library (STL) areadvanced subjects, there are some good books on the subject—for example,C Templates: The Complete Guide, by David Vandevoorde and Nicolai M.Josuttis; STL Tutorial and Reference Guide: C Programming with the StandardTemplate Library, Second Edition, by David R. Musser, Gillmer J. Derge, and AtulSaini; and Effective STL: 50 Specific Ways to Improve Your Use of the StandardTemplate Library, by Scott Meyers.And remember that Chapter 16 does introduce you to using STL, which provides extremely useful, existing templates for you to take advantage of.Getting Started with C : A Free CompilerAlthough this edition doesn’t come with a CD with a free compiler on it, that isno longer necessary. You can download some excellent shareware (that is, free)versions of C from the Internet that not only have a free compiler (that’s theapplication that translates your programs into machine-readable form) but alsoa very good development environment. And they install easily.To download this free software, start by going to the book’s Web site:www.informit.com/title/9780132673266.As mentioned earlier, you will also find downloadable copies of all the fullprogram examples in the book, as well as answers to exercises.A Final Note: Have Fun!Once again, there is nothing to fear about C . Yes, there are those nasty potholes I started out discussing, but remember, I’m going to steer you aroundthem. Admittedly, C is not a language for the weak of heart; it assumes youknow exactly what you’re doing. But it doesn’t have to be intimidating. I hopeyou use the practical examples and find the puzzles and games entertaining. Thisis a book about learning and about taking a road to new knowledge, but morethan that, it’s a book about enjoying the ride.

This page intentionally left blank

AcknowledgmentsI am likely to leave many deserving people out this time, but a few names cry outfor special mention. The book’s editor, Peter Gordon, not only took the initiativein arranging for the new edition but did a lovely job of nursing the book throughall its stages along with the author’s ego. His long-suffering right hand, KimBoedigheimer, was a better person than we all deserved, coming to the rescueagain and again and kindly aiding the author. I’d also like to extend a specialthanks to Kim Wimpsett and Anna Popick, who unexpectedly have been anabsolute delight to work with in getting the book through its final tense stages.Closer to home in the Seattle area: I also want to make special mention to veteran Microsoft programmers John R. Bennett and Matt Greig, who providedsuperb insights about the latest directions of C . Some of the more interestingnew sections in the book came about directly as a result of extended conversations with these experts.xxix

This page intentionally left blank

About the AuthorBrian Overland published his first article in a professional math journal at age 14.After graduating from Yale, he began workingon large commercial projects in C and Basic,including an irrigation-control system used allover the world. He also tutored students in math,computer programming, and writing, as well aslecturing to classes at Microsoft and at the community-college level. On the side, he found an outlet for his lifelong love of writing by publishingfilm and drama reviews in local newspapers. Hisqualifications as an author of technical books arenearly unique because they involve so much real programming and teachingexperience, as well as writing.In his 10 years at Microsoft, he was a tester, author, programmer, and manager. As a technical writer, he became an expert on advanced utilities, such as thelinker and assembler, and was the “go-to” guy for writing about new technology.His biggest achievement was probably organizing the entire documentation setfor Visual Basic 1.0 and having a leading role in teaching the “object-based” wayof programming that was so new at the time. He was also a member of the VisualC 1.0 team.Since then, he has been involved with the formation of new start-up companies (sometimes as CEO). He is currently working on a novel.xxxi

This page intentionally left blank

4Functions:Many AreCalledThe most fundamental building block in the programming toolkit is the function—often known as procedure or subroutine in other languages. A function is agroup of related statements that accomplish a specific task. Once you define afunction, you can execute it whenever you need to do so.Understanding functions is a crucial step to programming in C : Withoutfunctions, it would be a practical impossibility to engage in serious programmingprojects. Imagine how difficult it would be to write a word processor, for example, without some means of dividing the labor. Functions make this possible.The Concept of FunctionIf you’ve followed the bo

What the Heck Is a Pointer, Anyway? 145 The Concept of Pointer 146 Interlude What Do Addresses Look Like? 147 Declaring and Using Pointers 148 Example 6.1. Print Out Addresses 151 Example 6.2. The double_it Function 152 How It Works 153 Exercises 154 Swap: Another Function Using Pointe