IT training learn c on the mac (2nd ed ) mark bucanek 2012 12 19

502 285 0
IT training learn c on the mac (2nd ed ) mark  bucanek 2012 12 19

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

Thông tin tài liệu

BOOKS FOR PROFESSIONALS BY PROFESSIONALS® Companion eBook Available The perfect introduction for those new to programming, this book teaches you best practices using the latest tools and techniques You’ll learn how to the following: • Write and compile native C programs • Tap into the power of mathematical expressions with variables and operators • Empower your programs with pointers and parameters • Control the direction your program takes with flow control • Design your own custom data structures • Create your own command line tools • Save your program’s data and read it back in again • Handle errors if things happen to go wrong Considered a classic by an entire generation of Mac programmers, this new edition of Learn C on the Mac has been updated for the latest C standards, which are the foundation for all OS X and iOS app development Turn to Learn C on the Mac, and find the knowledge and skills that will help you master C programming A complete course on C programming for the beginner Learn C on the Mac S tart programming with Learn C on the Mac You don’t need to know anything about programming—not one little bit You’ll start with the basics and, guided by expert Mac developers, take small steps that will help you learn the essentials of C, the gateway to programming your Mac, iPhone, or iPad SECOND EDITION Mark Bucanek COMPANION eBOOK US $39.99 SOURCE CODE ONLINE www.apress.com Shelve in Mobile Computing User level: Beginning-Intermediate Learn C on the Mac For OS X and iOS SECOND EDITION David Mark | James Bucanek V413HAV For your convenience Apress has placed some of the front matter material after the index Please use the Bookmarks and Contents at a Glance links to access them Contents at a Glance  About the Authors .xiii  About the Technical Reviewer xiv  Acknowledgments xv  Introduction .xvi  Chapter 1: Go Get the Tools!  Chapter 2: Programming Basics 11  Chapter 3: C Basics: Statements and Functions 21  Chapter 4: C Basics: Variables and Operators 43  Chapter 5: Debugging 75  Chapter 6: Controlling Your Program’s Flow 93  Chapter 7: Pointers and Parameters 137  Chapter 8: More Data Types 177  Chapter 9: The Command Line 229  Chapter 10: Designing Your Own Data Structures 291  Chapter 11: Working With Files 331  Chapter 12: Handling Errors 381  Chapter 13: Advanced Topics 411  Chapter 14: Where Do You Go from Here? 455  Appendix: Answers to Excercises 467  Index 477 iv Introduction Welcome Aboard Welcome! Chances are that you are reading this because you love the Mac And not only you love the Mac, but you also love the idea of learning how to design and develop your very own Mac programs You’ve definitely come to the right place This book assumes that you know how to use your Mac That’s it You don’t need to know anything about programming—not one little bit We’ll start off with the basics, and each step we take will be a small one to make sure that you have no problem following along This book will focus on the basics of programming At the same time, you’ll learn the essentials of the C programming language In Douglas Adam’s book The Hitchhiker's Guide to the Galaxy, the answer to “the Ultimate Question of Life, the Universe, and Everything” is determined to be “42.” That answer is, of course, wrong; the correct answer is “C.” The C language is the wellspring of software The nothing-short-of-miraculous revolution in computing and consumer electronics over the past half century has largely been accomplished using C, languages that are direct descendants of C (Objective-C, C++), or languages designed to work like C (Java, C#) Learn C and the programming world is your oyster  Note Douglas Adams was a big Macintosh fan Once you get through this book, you’ll be ready to move on to object-oriented programming and Objective-C—the official programming language of OS X and iOS Does this all sound a little overwhelming? Not to worry; in this book, we’ll take small steps, so nobody gets lost You can definitely this! Who Is This Book For? When Dave wrote the very first edition of Learn C on the Mac back in 1991, he was writing with college students in mind After all, college was where he really learned to program It seems he was way off xvi INTRODUCTION “My first clue that I had underestimated my audience was when I started getting e-mails from fifth graders who were making their way through the book Fifth graders! And not just one but lots of nine-, ten-, and eleven-year-old kids were digging in and learning to program Cool! And the best part of all was when these kids started sending me actual shipping products that they created You can’t imagine how proud I was and still am.” Dave was really on to something Over the years, we’ve heard from soccer moms, hobbyists, even folks who were using the Mac for the very first time, all of whom made their way through Learn C on the Mac and came out the other end, proud, strong, and full of knowledge So what you need to know to get started? Although learning C by just reading a book is possible, you’ll get the most out of this book if you run each example program as you encounter it To this, you’ll need a Mac running OS X (preferably version 10.6.8 or later) and an Internet connection You’ll need the Internet connection to download the free tools Apple has graciously provided for anyone interested in programming the Mac and to download the projects that go along with this book Again, if you know nothing about programming, don’t worry The first few chapters of this book will bring you up to speed If you have some programming experience (or even a lot), you might want to skim the first few chapters, and then dig right into the C fundamentals that start in Chapter The Lay of the Land Here’s a quick tour of what’s to come in this book  Chapter shows you how to get the free software tools you’ll use throughout this book  Chapter explains some of the basics of how computer programs are built  Chapter shows you how to embed a series of programming statements into a reusable function, something you can call again and again  Chapter adds variables and operators into the mix, bringing the power of mathematical expressions into your programs  Chapter teaches you how to watch your program execute, line-by-line, to see that it’s doing the right thing, or fix it if it’s not  Chapter introduces the concept of flow control, using constructs like if, else, do, and while to control the direction your program takes  Chapter covers pointers and parameters, two concepts that will add a dramatic new level of power to your programs  Chapter moves beyond the simple data types used in the first half of the book, adding the ability to work with more complex numbers along with data types like arrays and text strings xvii INTRODUCTION  Chapter takes a break to show you how to deploy your finished program and use it from the command line  Chapter 10 dives even deeper into data and teaches you how to design your own custom data structures  Chapter 11 shows you how to save your program’s data and read it back in again by introducing the concept of the data file  Chapter 12 gives you some techniques for dealing with errors, for when things go wrong  Chapter 13 covers a variety of advanced topics—typecasting, unions, recursion, sorting, collections, and much more  Finally, Chapter 14 wraps things up and points you to the next step on your journey Ready to get started? Let’s go! xviii Chapter Go Get the Tools! If you want to build a house, you need a solid set of well-crafted tools Building computer programs is no different Programming requires a specialized set of development tools -basically, programs that make programs In the early days of C, you only needed a few, relatively simple tools As computers have become more sophisticated, so has the universe of development tools Today, it’s not uncommon to employ dozens of programs to create even a ‘‘simple’’ application: editors, compilers, linkers, debuggers, emulators, profilers, analyzers, and more Add to that list programs that help you find documentation, cross reference your code, record your development history, and, well, it’s starting to look like a whole hardware store full of tools! The good news is that Apple has come to your rescue Just as Apple has used an elegant user interface to demystify their most sophisticated applications, they’ve done the same for software developers (That’s you!) Installing Xcode Apple’s Xcode is a complete hardware store of software development tools, packaged and delivered as a single application All you have to is write your program and Xcode will -behind the scenes -direct the scores of individual development tools needed to turn your idea into reality It would make the Wizard of Oz proud NOTE: An application that organizes multiple development tools into a single workspace is called an integrated development environment (IDE) Xcode is an IDE CHAPTER 1: Go Get the Tools! And getting Xcode into your computer couldn’t be easier The entire Xcode development suite is available from the App Store Launch the App Store, go to the Developer Tools category (or just search for ‘‘Xcode’’), and click to install Xcode, as shown in Figure 1-1 Don’t worry if your screen looks a bit different than the figure Apple is constantly updating Xcode, so there will probably be a new version of Xcode in the App Store by the time this book hits the shelves (or your screen) Figure 1-1 Installing Xcode from the App Store That’s it! Sit back and wait for Xcode to download and install And you’re going to have to wait awhile, as it’s a really big application So amuse yourself with the rest of this chapter while it downloads Switch to the Purchases view, at the top of the App Store window, if you want see how the download is progressing How much is that IDE in the Window? Xcode has gone through various prices in the past Apple really wants you to create great applications and has strived, for the most part, to make its developments tools freely available It used to be that Xcode was only available to registered developers Becoming a registered developer usually costs money, so Xcode was ‘‘free’’ only in the sense that the prize inside a cereal box is ‘‘free.’’ For a while, Xcode was priced at $5 As of this writing, Xcode is free in the App Store Hopefully, it will stay that way CHAPTER 1: Go Get the Tools! NOTE: If you’re running an older version of OS X and don’t have access to the App Store, you can still download an earlier version of Xcode—but we don’t recommend it The first problem you’re going to encounter is how to get your copy of Xcode As of this writing, you must be a registered developer to obtain an older version of Xcode Unfortunately, Apple no longer offers free developer registration—largely because Xcode is now available for free in the App Store—so you’ll have to pay to register, and that can be expensive If you are a registered developer or have access to Apple’s University Program for higher education, you can log into http://developer.apple.com/ and download the tools But your biggest problem is going to be the differences between the current Xcode and older versions The code examples in this book will still work and make sense, but the commands, windows, features, and controls are all going to be substantially different You’re going to have to figure out a lot on your own We certainly don’t want to discourage anyone from learning C on the Mac, but we strongly recommend you upgrade to the latest version of OS X so you have access to the latest version of Xcode What’s a Registered Developer? So what’s a registered developer and you need to be one? The short answer is ‘‘not yet.’’ Becoming a registered developer grants you access to even more tools and resources than just Xcode But you don’t need any of that to write great applications for OS X or iOS! You don’t need it to use Xcode You certainly don’t need to be a registered developer to work through this book (or most other books, for that matter) You will need to become a registered developer if you want to sell, or even give away, your masterpieces on any of Apple’s app stores How cool would that be? You can register at any time, so there’s no hurry When you are ready, visit http://developer.apple.com/ CHAPTER 1: Go Get the Tools! Getting the Projects While you’re still waiting for Xcode to download and install, why not get the project files for this book? Everything you need to create the projects in this book is described in the text, but downloading the finished projects from the Apress web site will save you a lot of typing Go to http://www.apress.com/book/view/9781430245339 Below the book’s description, you’ll see some folder tabs, one of which is labeled Source Code/Downloads Click that tab Now find the link that downloads the projects for this book Click that link and a file named Learn C Projects.zip will download to your hard drive Locate the file Learn C Projects.zip in your Downloads folder (or wherever the browser saved it) Double-click the file to extract its contents, leaving you with a folder named Learn C Projects Move the folder wherever you like Using Xcode Once Xcode has finished installing, launch it as you would any application, from the dock or LaunchPad When first launched, Xcode will present its startup window (Figure 1-2) Learn C on the Mac For OS X and iOS ■■■ David Mark James Bucanek i Learn C on the Mac: For OS X and iOS Copyright © 2012 by David Mark and James Bucanek This work is subject to copyright All rights are reserved by the Publisher, whether the whole or part of the material is concerned, specifically the rights of translation, reprinting, reuse of illustrations, recitation, broadcasting, reproduction on microfilms or in any other physical way, and transmission or information storage and retrieval, electronic adaptation, computer software, or by similar or dissimilar methodology now known or hereafter developed Exempted from this legal reservation are brief excerpts in connection with reviews or scholarly analysis or material supplied specifically for the purpose of being entered and executed on a computer system, for exclusive use by the purchaser of the work Duplication of this publication or parts thereof is permitted only under the provisions of the Copyright Law of the Publisher's location, in its current version, and permission for use must always be obtained from Springer Permissions for use may be obtained through RightsLink at the Copyright Clearance Center Violations are liable to prosecution under the respective Copyright Law ISBN-13 (pbk): 978-1-4302-4533-9 ISBN-13 (electronic): 978-1-4302-4534-6 Trademarked names, logos, and images may appear in this book Rather than use a trademark symbol with every occurrence of a trademarked name, logo, or image we use the names, logos, and images only in an editorial fashion and to the benefit of the trademark owner, with no intention of infringement of the trademark The use in this publication of trade names, trademarks, service marks, and similar terms, even if they are not identified as such, is not to be taken as an expression of opinion as to whether or not they are subject to proprietary rights While the advice and information in this book are believed to be true and accurate at the date of publication, neither the authors nor the editors nor the publisher can accept any legal responsibility for any errors or omissions that may be made The publisher makes no warranty, express or implied, with respect to the material contained herein President and Publisher: Paul Manning Lead Editor: Steve Anglin Developmental Editor: James Markham Technical Reviewer: Michael Thomas Editorial Board: Steve Anglin, Mark Beckner, Ewan Buckingham, Gary Cornell, Louise Corrigan, Morgan Ertel, Jonathan Gennick, Jonathan Hassell, Robert Hutchinson, Michelle Lowman, James Markham, Matthew Moodie, Jeff Olson, Jeffrey Pepper, Douglas Pundick, Ben Renow-Clarke, Dominic Shakeshaft, Gwenan Spearing, Matt Wade, Tom Welsh Coordinating Editor: Jill Balzano Copy Editor: Mary Behr Compositor: Bytheway Publishing Services Indexer: SPi Global Artist: SPi Global Cover Designer: Anna Ishchenko Distributed to the book trade worldwide by Springer Science+Business Media New York, 233 Spring Street, 6th Floor, New York, NY 10013 Phone 1-800-SPRINGER, fax (201) 348-4505, e-mail orders-ny@springer-sbm.com, or visit www.springeronline.com Apress Media, LLC is a California LLC and the sole member (owner) is Springer Science + Business Media Finance Inc (SSBM Finance Inc) SSBM Finance Inc is a Delaware corporation For information on translations, please e-mail rights@apress.com, or visit www.apress.com Apress and friends of ED books may be purchased in bulk for academic, corporate, or promotional use eBook versions and licenses are also available for most titles For more information, reference our Special Bulk Sales–eBook Licensing web page at www.apress.com/bulk-sales Any source code or other supplementary materials referenced by the author in this text is available to readers at www.apress.com For detailed information about how to locate your book’s source code, go to www apress.com/source-code ii To Deneen, Daniel, Kelley, and Ryan, ILYANMWITWWA To Deborah, for making time Contents  About the Authors .xiii  About the Technical Reviewer xiv  Acknowledgments xv  Introduction .xvi  Chapter 1: Go Get the Tools! Installing Xcode How much is that IDE in the Window? What’s a Registered Developer? Getting the Projects Using Xcode Creating a New Xcode Project The Workspace Window Running a Project 10 Moving On 10  Chapter 2: Programming Basics 11 Programming .11 Some Alternatives to C 12 What About Objective-C, C#, C++, and Java? 12 What’s the Best Programming Language for the Mac or iOS Devices? .13 The Programming Process 14 Source Code 14 Compiling Your Source Code 16 Building Your Application .18 What’s Next? 19  Chapter 3: C Basics: Statements and Functions 21 C Statements 21 C Functions 22 v CONTENTS Defining a Function .23 Syntax Errors and Algorithms .23 Calling a Function .25 Same Program, Two Functions 28 The Hello2 Project 28 The Hello2 Source Code .30 Running Hello2 .32 Doing That Again, and Again, and Again 34 Generating Some Errors .35 Fixing the Problem 35 Getting Close 36 C is Case Sensitive .37 Exploring Xcode’s Built-In Manuals 39 Getting Help Quickly .41 What’s Next? 41  Chapter 4: C Basics: Variables and Operators 43 An Introduction to Variables .43 Working with Variables .45 Variable Names 45 The Size of a Type 47 Bytes and Bits .48 Going from Byte to Bytes 50 Operators 51 The +, -, ++, and Operators .52 The += and -= Operators .54 The *, /, %, *=, /=, and %= Operators 54 Using Parentheses .56 Operator Precedence 57 Sample Programs .59 Opening Operator.xcodeproj .59 Stepping Through the Operator Source Code .61 Opening Postfix.xcode 64 Stepping Through the Postfix Source Code 65 Sprucing Up Your Code 67 Source Code Spacing 67 Comment Your Code 69 The Curly Brace Controversy 71 What’s Next? 72  Chapter 5: Debugging 75 vi What’s a Debugger? 76 CONTENTS Controlling Execution 77 Setting Breakpoints 78 Stepping Over a Statement 80 Stepping Into a Function .81 Stepping Out of a Function 84 Full Speed Ahead 85 Examining Variables 87 How is a Debugger like an Iceberg? 90 What’s Next? 90  Chapter 6: Controlling Your Program’s Flow 93 Flow Control 93 The if Statement 94 Expressions 95 True Expressions 96 Comparative Operators .97 Logical Operators 98 TruthTester.xcodeproj 102 Compound Expressions 102 Statements .103 The Curly Braces 104 Where to Place the Semicolon 106 Two Common Pitfalls 106 The while Statement 110 The for Statement 113 LoopTester.xcodeproj 116 The Statement .119 The switch Statement 120 A case with No Statements 122 The Mixed Blessing of Fall-Through 123 switch Wrap-Up 124 Breaks in Loops 125 The continue Statement 125 IsOdd.xcodeproj 126 Stepping Through the IsOdd Source Code 127 NextPrime.xcodeproj 129 Stepping Through the NextPrime Source Code 130 What’s Next? 134 vii CONTENTS  Chapter 7: Pointers and Parameters 137 What Is a Pointer? 138 Why Use Pointers? 138 Checking Out of the Library 141 Pointer Basics 141 The Address of a Variable 142 The & Operator 144 Declaring a Pointer Variable .144 The * Operator 145 Function Parameters 152 Variable Scope 152 How Function Parameters Work 153 Parameters Are Temporary 155 The Difference Between Arguments and Parameters 156 Function Return Value 157 printf() Returns a Value .158 Multiple Return Statements 159 Returning Nothing at All .160 Putting it All Together 161 Using Pointers as Parameters 161 Factor.xcodeproj .163 Some Pointers on Pointers .165 Pass-By-Value vs Pass-By-Reference .165 The NULL Pointer Value 166 The Dark Side of Pointers 167 Global and Static Variables 169 Global Variables 169 Adding Globals to Your Programs .171 Static Variables 172 What’s Next? 174  Chapter 8: More Data Types 177 Data Types Beyond Int .177 FloatSizer 178 The Integer Types .186 IntSizer.xcodeproj .188 The Long and Short of ints 189 The Best int for the Job 194 Semantic Types 195 Exact-Width Types 195 Integer vs Floating Point 196 viii CONTENTS Working with Characters 197 The ASCII Character Set .197 ASCII.xcodeproj 198 Stepping Through the ASCII Source Code 202 Arrays .204 Why Use Arrays? .205 Dice.xcode 205 Stepping Through the Dice Source Code 207 Danger, Will Robinson! .209 The #define Directive 210 Using #defines in Your Code .212 Stepping Through the Preprocessor 213 The Advantages of Using #define Directives 214 Function-like #define Macros 216 Text Strings 217 A Text String in Memory .217 FullName.xcodeproj 218 Overflow.xcodeproj 223 What’s Next? 225  Chapter 9: The Command Line 229 Command Line Basics 230 Command Arguments .232 Learning More About Commands .233 Where Shell Commands Come From 235 Creating a Command-Line Tool 236 Command Arguments and main() .237 SeeArgs.xcodeproj 238 Deploying the Program 241 Using Paths 244 Current Directory and Relative Paths 245 Special Directory Names 246 The Home Directory Name 248 Installing a Command-Line Tool 248 Creating a Private bin Directory 250 Installing the Tool .250 Configuring the PATH Variable 251 Character Input 252 Pipes 252 Redirection 253 Namer.xcodeproj 257 ix CONTENTS Pointer Arithmetic 264 Comparing Pointers 264 Pointer Addition 265 Subtracting Pointers 268 WordCount.xcodeproj .268 Stepping Through the WordCount Source Code 269 Testing WordCount in the Shell 278 RomanNumeral.xcodeproj 281 main() 281 NumberToRomanNumeral() 282 One Last Word About the Command-Line Interface 287 What’s Next? 288  Chapter 10: Designing Your Own Data Structures 291 Bundling Data 291 Model A: Three Arrays 292 MultiArray.xcodeproj 293 Model B: The Structure Approach 300 StructSize.xcodeproj 302 Passing a struct As a Parameter 307 Passing a Copy of the struct .308 ParamAddress.xcodeproj 309 struct Arrays 311 Allocating Your Own Memory 312 Using malloc() 313 free() 315 Keeping Track of That Address! 316 Working with Linked Lists 317 Why Use Linked Lists? 318 Creating a Linked List .318 DVDTracker.xcodeproj 319 Stepping Through the DVDTracker Source Code 321 What’s Next? 329  Chapter 11: Working With Files 331 What Is a Data File? 332 File Basics 332 Understanding File Names 332 Opening and Closing a File 333 Reading a File 335 x CONTENTS PrintFile.xcodeproj .337 Stepping Through the PrintFile Source Code 339 Writing Files .342 DVDFiler.xcodeproj .343 Fancier File Manipulation 358 The Update Modes 358 Random File Access 359 Using Random Access Functions .359 DinoEdit.xcodeproj 360 Text vs Data Files 368 Working with Endians .369 Making RomanNumeral a Better Tool 371 Stepping Through RomanNumeral.xcodeproj 372 Putting RomanNumeral Through Its Paces .376 File System Objects 378 What’s Next? 379  Chapter 12: Handling Errors 381 Murphy’s Law 382 Rule #1: Never Assume 383 Assumptions About Variables .383 Check Ranges 385 Tolerate All Possible Values 386 Assert Your Assumptions 388 Rule #2: Stay Alert .390 Pay Attention to Return Values 391 errno 392 Rule #3: Have an Escape Plan 394 Follow the Success 395 Early Return 397 Skip Past Failure .398 Percolate Errors Up 401 Exit, Stage Left 402 The Long Jump 403 Rule #4: Anticipate Problems 407 Rule #5: Pick Your Battles 409 What’s Next? 409  Chapter 13: Advanced Topics 411 Type Conversion .411 Conversion Rules 413 xi CONTENTS Conversion Warnings 415 Typecasting 416 Typecasting Pointers 417 const Modifier 419 Creating Your Own Types 420 struct typedefs 422 Forward References 422 Enumerated Types .423 Unions 425 Why Use Unions? 427 Recursion 428 The Iterative Approach .429 A Recursive Approach 430 Function Pointers .433 The Remaining Operators 435 Getting More From The Libraries .438 Sorting with the Standard Library 438 Collections in Core Foundation 445 What’s Next? 452  Chapter 14: Where Do You Go from Here? 455 The Mac User Interface 455 Learning Objective-C 456 Learning Cocoa and Cocoa Touch 457 A Bit of OS X Code 457 A Quick iOS App 460 Just a Touch of Objective-C .463 Go Get ‘Em 465  Appendix: Answers to Excercises 467  Index 477 xii About the Authors  Dave Mark is a longtime Mac developer and author who has written a number of books on Mac and iOS development, including Beginning iPhone Development (Apress, 2011), More iPhone Development (Apress, 2010), Learn C on the Mac (Apress, 2008), Ultimate Mac Programming (Wiley, 1995), and the Macintosh Programming Primer series (Addison-Wesley, 1992) Dave was one of the founders of MartianCraft, an iOS and Android development house Dave loves the water and spends as much time as possible on it, in it, or near it He lives with his wife and three children in Virginia  James Bucanek has spent the past 30 years programming and developing microprocessor systems He has experience with a broad range of computer hardware and software, from embedded consumer products to industrial robotics His development projects include the first local area network for the Apple II, distributed air conditioning control systems, a piano teaching system, digital oscilloscopes, silicon wafer deposition furnaces, and collaborative writing tools for K-12 education James holds a Java Developer Certification from Sun Microsystems and was awarded a patent for optimizing local area networks James is currently focused on OS X and iOS software development, where he can combine his deep knowledge of UNIX and object-oriented languages with his passion for elegant design James holds an Associate's degree in classical ballet from the Royal Academy of Dance xiii About the Technical Reviewer  Michael Thomas has worked in software development for over 20 years as an individual contributor, Team Lead, Program Manager, and Vice President of Engineering Michael has over 10 years experience working with mobile devices His current focus is in the medical sector using mobile devices to accelerate information transfer between patients and health care providers xiv Acknowledgments This book could not have been written without the support of our wonderful families Deneen, Daniel, Kelley, Ryan, Deborah, Doug, and Amber, thank you all for everything you’ve done for us We truly are lucky men Many, many thanks to the fine folks at Apress Clay Andres started this ball rolling by bringing both Dave and James over to Apress Steve Anglin is largely responsible for deciding what Apress prints, and we are flattered by his continued conviction in this book James Markham kept a watchful eye on every paragraph, keeping our message clear and comprehensible Michael Thomas checked every line of code and symbol to ensure complete accuracy Any technical errors are ultimately our responsibility, but there are significantly fewer thanks to Michael Mary Behr dotted our i's, crossed our t’s, corrected our spelling, and made sure we used “whom” correctly If you find this book easy to read, you have Mary’s blue pencil to thank Anna Ishchenko designed our beautiful cover Last, but certainly not least, we are indebted to Coordinating Editor Jill Balzano who managed to juggle schedules, coordinate editors, track production, and herd two headstrong authors towards a common goal To all the folks at Apress, thank you, thank you, thank you! Dave says: A very special shout out goes to James, my incredibly talented co-author James made many important technical contributions to this book, helping me scrub the prose and the sample code to ensure that it followed the C standard to the letter He also added many concepts to the book that are vital to any aspiring programmer And from James: I am most grateful to David Mark for allowing me the opportunity to contribute to this venerable title Dave has made learning C engaging and enjoyable for an entire generation of programmers It’s been an honor contributing to that institution I would also like to extend thanks to Apple’s Xcode development team for continually improving one of the finest software development tools in the world xv ... of the statements inside MyFunction () to be executed, one after the other Once the last statement in MyFunction () is executed, control is returned to main () Next, main () calls AnotherFunction (). .. book, then learn Objective -C and Cocoa (for the Mac) or Cocoa Touch (for iOS devices) Objective -C is a programming language based on C Everything you learn about C will apply to Objective -C Objective -C. .. function is executed Confused? Don’t worry, you’ll get there Look at Figure 3-2 In this example, main () starts with a call to the function MyFunction () This call to MyFunction () will cause each

Ngày đăng: 05/11/2019, 15:40

Từ khóa liên quan

Mục lục

  • Cover

    • Contents at a Glance

    • Contents

    • About the Authors

    • About the Technical Reviewer

    • Acknowledgments

    • Introduction

  • Chapter 1 Go Get the Tools!

    • Installing Xcode

    • How much is that IDE in the Window?

    • What’s a Registered Developer?

    • Getting the Projects

    • Using Xcode

      • Creating a New Xcode Project

      • The Workspace Window

      • Running a Project

    • Moving On

  • Chapter 2 Programming Basics

    • Programming

      • Some Alternatives to C

      • What About Objective-C, C#, C++, and Java?

    • What’s the Best Programming Language for the Mac or iOS Devices?

    • The Programming Process

      • Source Code

      • Compiling Your Source Code

      • Building Your Application

    • What’s Next?

  • Chapter 3 C Basics: Statements and Functions

    • C Statements

    • C Functions

      • Defining a Function

      • Syntax Errors and Algorithms

      • Calling a Function

    • Same Program, Two Functions

      • The Hello2 Project

      • The Hello2 Source Code

      • Running Hello2

    • Doing That Again, and Again, and Again

    • Generating Some Errors

      • Fixing the Problem

      • Getting Close

      • C is Case Sensitive

    • Exploring Xcode’s Built-In Manuals

      • Getting Help Quickly

    • What’s Next?

  • Chapter 4 C Basics: Variables and Operators

    • An Introduction to Variables

      • Working with Variables

      • Variable Names

      • The Size of a Type

      • Bytes and Bits

      • Going from 1 Byte to 2 Bytes

    • Operators

      • The +, -, ++, and -- Operators

      • The += and -= Operators

      • The *, /, %, *=, /=, and %= Operators

    • Using Parentheses

    • Operator Precedence

    • Sample Programs

      • Opening Operator.xcodeproj

      • Stepping Through the Operator Source Code

      • Opening Postfix.xcode

      • Stepping Through the Postfix Source Code

    • Sprucing Up Your Code

      • Source Code Spacing

      • Comment Your Code

      • The Curly Brace Controversy

    • What’s Next?

  • Chapter 5 Debugging

    • What’s a Debugger?

    • Controlling Execution

      • Setting Breakpoints

      • Stepping Over a Statement

      • Stepping Into a Function

      • Stepping Out of a Function

      • Full Speed Ahead

    • Examining Variables

    • How is a Debugger like an Iceberg?

    • What’s Next?

  • Chapter 6 Controlling Your Program’s Flow

    • Flow Control

      • The if Statement

    • Expressions

      • True Expressions

      • Comparative Operators

      • Logical Operators

      • TruthTester.xcodeproj

    • Compound Expressions

    • Statements

      • The Curly Braces

      • Where to Place the Semicolon

      • Two Common Pitfalls

    • The while Statement

    • The for Statement

      • LoopTester.xcodeproj

    • The do Statement

    • The switch Statement

      • A case with No Statements

      • The Mixed Blessing of Fall-Through

      • switch Wrap-Up

    • Breaks in Loops

    • The continue Statement

    • IsOdd.xcodeproj

      • Stepping Through the IsOdd Source Code

    • NextPrime.xcodeproj

      • Stepping Through the NextPrime Source Code

    • What’s Next?

  • Chapter 7 Pointers and Parameters

    • What Is a Pointer?

      • Why Use Pointers?

      • Checking Out of the Library

    • Pointer Basics

      • The Address of a Variable

      • The & Operator

      • Declaring a Pointer Variable

      • The * Operator

    • Function Parameters

      • Variable Scope

      • How Function Parameters Work

      • Parameters Are Temporary

      • The Difference Between Arguments and Parameters

    • Function Return Value

      • printf() Returns a Value

      • Multiple Return Statements

      • Returning Nothing at All

    • Putting it All Together

      • Using Pointers as Parameters

      • Factor.xcodeproj

    • Some Pointers on Pointers

      • Pass-By-Value vs. Pass-By-Reference

      • The NULL Pointer Value

      • The Dark Side of Pointers

    • Global and Static Variables

      • Global Variables

      • Adding Globals to Your Programs

      • Static Variables

      • What’s Next?

  • Chapter 8 More Data Types

    • Data Types Beyond Int

      • FloatSizer

      • The Integer Types

      • IntSizer.xcodeproj

      • The Long and Short of ints

    • The Best int for the Job

      • Semantic Types

      • Exact-Width Types

      • Integer vs. Floating Point

    • Working with Characters

      • The ASCII Character Set

      • ASCII.xcodeproj

      • Stepping Through the ASCII Source Code

    • Arrays

      • Why Use Arrays?

      • Dice.xcode

      • Stepping Through the Dice Source Code

      • Danger, Will Robinson!

    • The #define Directive

      • Using #defines in Your Code

      • Stepping Through the Preprocessor

      • The Advantages of Using #define Directives

      • Function-like #define Macros

    • Text Strings

      • A Text String in Memory

      • FullName.xcodeproj

      • Overflow.xcodeproj

    • What’s Next?

  • Chapter 9 The Command Line

    • Command Line Basics

      • Command Arguments

      • Learning More About Commands

      • Where Shell Commands Come From

    • Creating a Command-Line Tool

      • Command Arguments and main()

      • SeeArgs.xcodeproj

    • Deploying the Program

    • Using Paths

      • Current Directory and Relative Paths

      • Special Directory Names

      • The Home Directory Name

    • Installing a Command-Line Tool

      • Creating a Private bin Directory

      • Installing the Tool

      • Configuring the PATH Variable

    • Character Input

      • Pipes

      • Redirection

      • Namer.xcodeproj

    • Pointer Arithmetic

      • Comparing Pointers

      • Pointer Addition

      • Subtracting Pointers

    • WordCount.xcodeproj

      • Stepping Through the WordCount Source Code

      • Testing WordCount in the Shell

    • RomanNumeral.xcodeproj

      • main()

      • NumberToRomanNumeral()

    • One Last Word About the Command-Line Interface

    • What’s Next?

  • Chapter 10 Designing Your Own Data Structures

    • Bundling Data

    • Model A: Three Arrays

      • MultiArray.xcodeproj

    • Model B: The Structure Approach

      • StructSize.xcodeproj

    • Passing a struct As a Parameter

      • Passing a Copy of the struct

    • ParamAddress.xcodeproj

    • struct Arrays

    • Allocating Your Own Memory

      • Using malloc()

      • free()

      • Keeping Track of That Address!

    • Working with Linked Lists

      • Why Use Linked Lists?

      • Creating a Linked List

    • DVDTracker.xcodeproj

      • Stepping Through the DVDTracker Source Code

    • What’s Next?

  • Chapter 11 Working With Files

    • What Is a Data File?

    • File Basics

      • Understanding File Names

      • Opening and Closing a File

    • Reading a File

    • PrintFile.xcodeproj

      • Stepping Through the PrintFile Source Code

    • Writing Files

      • DVDFiler.xcodeproj

    • Fancier File Manipulation

      • The Update Modes

      • Random File Access

      • Using Random Access Functions

      • DinoEdit.xcodeproj

      • Text vs. Data Files

      • Working with Endians

    • Making RomanNumeral a Better Tool

      • Stepping Through RomanNumeral.xcodeproj

      • Putting RomanNumeral Through Its Paces

    • File System Objects

    • What’s Next?

  • Chapter 12 Handling Errors

    • Murphy’s Law

    • Rule #1: Never Assume

      • Assumptions About Variables

      • Check Ranges

      • Tolerate All Possible Values

      • Assert Your Assumptions

    • Rule #2: Stay Alert

      • Pay Attention to Return Values

      • errno

    • Rule #3: Have an Escape Plan

      • Follow the Success

      • Early Return

      • Skip Past Failure

      • Percolate Errors Up

      • Exit, Stage Left

      • The Long Jump

    • Rule #4: Anticipate Problems

    • Rule #5: Pick Your Battles

    • What’s Next?

  • Chapter 13 Advanced Topics

    • Type Conversion

      • Conversion Rules

      • Conversion Warnings

    • Typecasting

      • Typecasting Pointers

    • const Modifier

    • Creating Your Own Types

      • struct typedefs

      • Forward References

    • Enumerated Types

    • Unions

      • Why Use Unions?

    • Recursion

      • The Iterative Approach

      • A Recursive Approach

    • Function Pointers

    • The Remaining Operators

    • Getting More From The Libraries

      • Sorting with the Standard Library

      • Collections in Core Foundation

    • What’s Next?

  • Chapter 14 Where Do You Go from Here?

    • The Mac User Interface

      • Learning Objective-C

      • Learning Cocoa and Cocoa Touch

    • A Bit of OS X Code

    • A Quick iOS App

    • Just a Touch of Objective-C

    • Go Get ‘Em

  • Appendix: Answers to Exercises

  • Index

    • Numers and Symbols

    • A

    • B

    • C

    • D

    • E

    • F

    • G

    • H

    • I, J

    • K

    • L

    • M

    • N

    • O

    • P

    • Q

    • R

    • S

    • T

    • U

    • V

    • W

    • X, Y

    • Z

Tài liệu cùng người dùng

  • Đang cập nhật ...

Tài liệu liên quan