Đây là quyển sách tiếng anh về lĩnh vực công nghệ thông tin cho sinh viên và những ai có đam mê. Quyển sách này trình về lý thuyết ,phương pháp lập trình cho ngôn ngữ C và C++.
Trang 1800 East 96th St., Indianapolis, Indiana, 46240 USA
Primer Plus
Fifth Edition C
Stephen Prata
Trang 2C Primer Plus
Copyright © 2005 by Sams Publishing
All rights reserved No part of this book shall be reproduced, stored in a retrieval system,
or transmitted by any means, electronic, mechanical, photocopying, recording, or otherwise,
without written permission from the publisher No patent liability is assumed with respect
to the use of the information contained herein Although every precaution has been taken
in the preparation of this book, the publisher and author assume no responsibility for errors
or omissions Nor is any liability assumed for damages resulting from the use of the
infor-mation contained herein.
International Standard Book Number: 0-672-32696-5
Library of Congress Catalog Card Number: 2004095068
Printed in the United States of America
First Printing: November, 2004
Trademarks
All terms mentioned in this book that are known to be trademarks or service marks have
been appropriately capitalized Sams Publishing cannot attest to the accuracy of this
infor-mation Use of a term in this book should not be regarded as affecting the validity of any
trademark or service mark.
Warning and Disclaimer
Every effort has been made to make this book as complete and as accurate as possible, but
no warranty or fitness is implied The information provided is on an “as is” basis
Bulk Sales
Sams Publishing offers excellent discounts on this book when ordered in quantity for bulk
purchases or special sales For more information, please contact
U.S Corporate and Government Sales
Trang 3CONTENTS AT A GLANCE
C H A P T E R 1 Getting Ready 1
C H A P T E R 2 Introducing C 23
C H A P T E R 3 Data and C 49
C H A P T E R 4 Character Strings and Formatted Input/Output 89
C H A P T E R 5 Operators, Expressions, and Statements 129
C H A P T E R 6 C Control Statements: Looping 169
C H A P T E R 7 C Control Statements: Branching and Jumps 221
C H A P T E R 8 Character Input/Output and Input Validation 271
C H A P T E R 9 Functions 303
C H A P T E R 1 0 Arrays and Pointers 347
C H A P T E R 1 1 Character Strings and String Functions 399
C H A P T E R 1 2 Storage Classes, Linkage, and Memory Management 453
C H A P T E R 1 3 File Input/Output 499
C H A P T E R 1 4 Structures and Other Data Forms 535
C H A P T E R 1 5 Bit Fiddling 597
C H A P T E R 1 6 The C Preprocessor and the C Library 629
C H A P T E R 1 7 Advanced Data Representation 681
A P P E N D I X E S A P P E N D I X A Answers to the Review Questions 759
A P P E N D I X B Reference Section 799
Trang 4TABLE OF CONTENTS
C H A P T E R 1 Getting Ready .1
Whence C? .1
Why C? .2
Design Features .2
Efficiency .2
Portability .3
Power and Flexibility .3
Programmer Oriented .3
Shortcomings 4
Whither C? 4
What Computers Do .5
High-level Computer Languages and Compilers .6
Using C: Seven Steps .7
Step 1: Define the Program Objectives .8
Step 2: Design the Program .8
Step 3: Write the Code 8
Step 4: Compile .9
Step 5: Run the Program .9
Step 6: Test and Debug the Program .9
Step 7: Maintain and Modify the Program .10
Commentary .10
Programming Mechanics .10
Object Code Files, Executable Files, and Libraries .11
Unix System 13
Linux System .14
Integrated Development Environments (Windows) .15
DOS Compilers for the IBM PC .16
C on the Macintosh .17
Language Standards .17
The First ANSI/ISO C Standard .17
The C99 Standard .18
How This Book Is Organized .19
Conventions Used in This Book .19
Typeface .19
Program Output 20
Special Elements .21
Trang 5Summary .22
Review Questions .22
Programming Exercise .22
C H A P T E R 2 Introducing C .23
A Simple Example of C 23
The Example Explained .24
Pass 1: Quick Synopsis .24
Pass 2: Program Details .26
The Structure of a Simple Program .35
Tips on Making Your Programs Readable .36
Taking Another Step in Using C .37
Documentation .37
Multiple Declarations 38
Multiplication .38
Printing Multiple Values 38
While You’re at It—Multiple Functions .38
Introducing Debugging 40
Syntax Errors .41
Semantic Errors .41
Program State 42
Keywords and Reserved Identifiers .43
Key Concepts .44
Summary .45
Review Questions .45
Programming Exercises 47
C H A P T E R 3 Data and C 49
A Sample Program .49
What’s New in This Program? .51
Data Variables and Constants .52
Data: Data-Type Keywords .52
Integer Versus Floating-Point Types .54
The Integer .54
The Floating-Point Number .54
Basic C Data Types .55
TheintType .55
Other Integer Types .59
Using Characters: Type char 64
The_BoolType .70
Portable Types: inttypes.h 70
Types float,double, and longdouble .72
Trang 6Complex and Imaginary Types .76
Beyond the Basic Types .77
Type Sizes .79
Using Data Types .80
Arguments and Pitfalls .81
One More Example: Escape Sequences .83
What Happens When the Program Runs .83
Flushing the Output .84
Key Concepts .85
Summary .85
Review Questions .86
Programming Exercises 88
C H A P T E R 4 Character Strings and Formatted Input/Output .89
Introductory Program .89
Character Strings: An Introduction .91
Type charArrays and the Null Character .91
Using Strings .92
Thestrlen()Function .93
Constants and the C Preprocessor .95
The const Modifier 98
Manifest Constants on the Job .98
Exploring and Exploiting printf()andscanf() 101
Theprintf()Function .101
Usingprintf() 102
Conversion Specification Modifiers for printf() 104
What Does a Conversion Specification Convert? .110
Usingscanf() 116
The*Modifier with printf()andscanf() 120
Usage Tips for printf() 122
Key Concepts .123
Summary .124
Review Questions .124
Programming Exercises 127
C H A P T E R 5 Operators, Expressions, and Statements 129
Introducing Loops .129
Fundamental Operators .132
Assignment Operator: = 132
Addition Operator: + 134
Subtraction Operator: – 134
Trang 7Sign Operators: –and+ 134
Multiplication Operator: * 135
Division Operator: / 137
Operator Precedence .138
Precedence and the Order of Evaluation .140
Some Additional Operators .141
ThesizeofOperator and the size_tType .142
Modulus Operator: % 142
Increment and Decrement Operators: ++and 144
Decrementing: 148
Precedence 149
Don’t Be Too Clever .149
Expressions and Statements .150
Expressions .150
Statements .151
Compound Statements (Blocks) 154
Type Conversions .156
The Cast Operator .158
Function with Arguments 159
A Sample Program .161
Key Concepts .163
Summary .163
Review Questions .164
Programming Exercises 167
C H A P T E R 6 C Control Statements: Looping .169
Revisiting the whileLoop .170
Program Comments .170
C-Style Reading Loop .172
ThewhileStatement .172
Terminating a whileLoop .173
When a Loop Terminates .174
while: An Entry-Condition Loop 174
Syntax Points .175
Which Is Bigger: Using Relational Operators and Expressions .176
What Is Truth? .178
What Else Is True? .179
Troubles with Truth .180
The New _BoolType .182
Precedence of Relational Operators .183
Trang 8Indefinite Loops and Counting Loops 186
TheforLoop .187
Usingforfor Flexibility 188
More Assignment Operators: +=,-=,*=,/=,%= 193
The Comma Operator .193
Zeno Meets the forLoop 196
An Exit-Condition Loop: do while 198
WhichLoop? .201
Nested Loops .201
Program Discussion .202
A Nested Variation .202
Introducing Arrays .203
Using a forLoop with an Array 205
A Loop Example Using a Function Return Value .207
Program Discussion .209
Using Functions with Return Values .210
Key Concepts .211
Summary .211
Review Questions .212
Programming Exercises 217
C H A P T E R 7 C Control Statements: Branching and Jumps .221
TheifStatement .222
Addingelseto the ifStatement .224
Another Example: Introducing getchar()andputchar() 225
Thectype.hFamily of Character Functions .228
Multiple Choice else if 230
Pairingelsewithif 233
More Nested ifs 234
Let’s Get Logical .238
Alternate Spellings: The iso646.hHeader File .239
Precedence 240
Order of Evaluation .240
Ranges .242
A Word-Count Program .242
The Conditional Operator: ?: 246
Loop Aids: continueandbreak 248
ThecontinueStatement .248
ThebreakStatement .251
Multiple Choice: switchand break 253
Using the switchStatement 255
Reading Only the First Character of a Line 256
Trang 9Multiple Labels .257
switchandif else 259
ThegotoStatement .259
Avoiding goto 260
Key Concepts .263
Summary .263
Review Questions .264
Programming Exercises 267
C H A P T E R 8 Character Input/Output and Input Validation .271
Single-Character I/O: getchar()andputchar() 272
Buffers .273
Terminating Keyboard Input 274
Files, Streams, and Keyboard Input .274
The End of File .275
Redirection and Files .278
Unix, Linux, and DOS Redirection 279
Creating a Friendlier User Interface .283
Working with Buffered Input .283
Mixing Numeric and Character Input .285
Input Validation .288
Analyzing the Program 292
The Input Stream and Numbers 293
Menu Browsing .293
Tasks .294
Toward a Smoother Execution .294
Mixing Character and Numeric Input .296
Key Concepts .299
Summary .299
Review Questions .300
Programming Exercises 301
C H A P T E R 9 Functions 303
Reviewing Functions .303
Creating and Using a Simple Function .304
Analyzing the Program 305
Function Arguments .308
Defining a Function with an Argument: Formal Parameters .309
Prototyping a Function with Arguments .310
Calling a Function with an Argument: Actual Arguments 311
The Black-Box Viewpoint 311
Returning a Value from a Function with return 312
Function Types .315
Trang 10ANSI C Function Prototyping 316
The Problem .316
The ANSI Solution 318
No Arguments and Unspecified Arguments .319
Hooray for Prototypes .320
Recursion .320
Recursion Revealed .320
Recursion Fundamentals .322
Tail Recursion .323
Recursion and Reversal .325
Recursion Pros and Cons .327
Compiling Programs with Two or More Source Code Files .328
Unix .328
Linux .328
DOS Command-Line Compilers .329
Windows and Macintosh Compilers .329
Using Header Files 329
Finding Addresses: The &Operator .333
Altering Variables in the Calling Function 334
Pointers: A First Look 336
The Indirection Operator: * 337
Declaring Pointers .338
Using Pointers to Communicate Between Functions .339
Key Concepts .343
Summary .343
Review Questions .343
Programming Exercises 345
C H A P T E R 1 0 Arrays and Pointers .347
Arrays 347
Initialization 348
Designated Initializers (C99) .352
Assigning Array Values 353
Array Bounds .354
Specifying an Array Size 355
Multidimensional Arrays .356
Initializing a Two-Dimensional Array .359
More Dimensions 360
Pointers and Arrays .361
Functions, Arrays, and Pointers .364
Using Pointer Parameters .366
Comment: Pointers and Arrays .369
Trang 11Pointer Operations .369
Protecting Array Contents 374
Usingconstwith Formal Parameters 374
More About const 376
Pointers and Multidimensional Arrays .378
Pointers to Multidimensional Arrays .381
Pointer Compatibility 382
Functions and Multidimensional Arrays 383
Variable-Length Arrays (VLAs) .386
Compound Literals 390
Key Concepts .393
Summary .393
Review Questions .395
Programming Exercises 397
C H A P T E R 1 1 Character Strings and String Functions .399
Representing Strings and String I/O .399
Defining Strings Within a Program 401
Pointers and Strings .407
String Input .409
Creating Space .409
Thegets()Function .410
Thefgets()Function .412
Thescanf()Function .413
String Output .414
Theputs()Function .415
Thefputs()Function .416
Theprintf()Function .417
The Do-It-Yourself Option .417
String Functions .420
Thestrlen()Function .420
Thestrcat()Function .421
Thestrncat()Function .422
Thestrcmp()Function .423
Thestrncmp()Variation .427
Thestrcpy()andstrncpy()Functions .428
Thesprintf()Function .433
Other String Functions .434
A String Example: Sorting Strings 436
Sorting Pointers Instead of Strings .437
The Selection Sort Algorithm .438
Trang 12Thectype.hCharacter Functions and Strings .439
Command-Line Arguments .441
Command-Line Arguments in Integrated Environments .443
Command-Line Arguments with the Macintosh .443
String-to-Number Conversions 444
Key Concepts .446
Summary .447
Review Questions .448
Programming Exercises 451
C H A P T E R 1 2 Storage Classes, Linkage, and Memory Management .453
Storage Classes .453
Scope .454
Linkage .455
Storage Duration .456
Automatic Variables .457
Register Variables .461
Static Variables with Block Scope .461
Static Variables with External Linkage .463
Static Variables with Internal Linkage 468
Multiple Files 468
Storage-Class Specifiers .469
Storage Classes and Functions .471
Which Storage Class? 472
A Random-Number Function and a Static Variable 472
Roll ’Em .476
Allocated Memory: malloc()andfree() 480
The Importance of free() 483
Thecalloc()Function .484
Dynamic Memory Allocation and Variable-Length Arrays .485
Storage Classes and Dynamic Memory Allocation .486
ANSI C Type Qualifiers 486
TheconstType Qualifier .486
ThevolatileType Qualifier .489
TherestrictType Qualifier .490
New Places for Old Keywords .491
Key Concepts .492
Summary .492
Review Questions .493
Programming Exercises 495
Trang 13C H A P T E R 1 3 File Input/Output .499
Communicating with Files .499
What Is a File? .500
The Text View and the Binary View .500
Levels of I/O .501
Standard Files .501
Standard I/O 502
Checking for Command-Line Arguments 503
Thefopen()Function .504
Thegetc()andputc()Functions 505
End-of-File .505
Thefclose()Function .507
Pointers to the Standard Files 507
A Simple-Minded File-Condensing Program 507
File I/O: fprintf(),fscanf(),fgets(), and fputs() 509
Thefprintf()andfscanf()Functions .509
Thefgets()andfputs()Functions 511
Commentary: gets()andfgets() 513
Adventures in Random Access: fseek()andftell() 513
Howfseek()andftell()Work .514
Binary Versus Text Mode .516
Portability .516
Thefgetpos()andfsetpos()Functions .517
Behind the Scenes with Standard I/O .517
Other Standard I/O Functions .518
Theint ungetc(int c, FILE *fp)Function .519
Theint fflush()Function .519
Theint setvbuf()Function .519
Binary I/O: fread()andfwrite() 520
Thesize_t fwrite()Function .521
Thesize_t fread()Function .522
Theint feof(FILE *fp)andint ferror(FILE *fp)Functions .522
Anfread()andfwrite()Example .523
Random Access with Binary I/O 525
Key Concepts .527
Summary .528
Review Questions .529
Programming Exercises 530
C H A P T E R 1 4 Structures and Other Data Forms .535
Sample Problem: Creating an Inventory of Books .535
Setting Up the Structure Declaration .537
Trang 14Defining a Structure Variable .538
Initializing a Structure .539
Gaining Access to Structure Members .540
Designated Initializers for Structures .540
Arrays of Structures .541
Declaring an Array of Structures .543
Identifying Members of an Array of Structures .543
Program Discussion .544
Nested Structures .545
Pointers to Structures .547
Declaring and Initializing a Structure Pointer 548
Member Access by Pointer .549
Telling Functions About Structures 550
Passing Structure Members .550
Using the Structure Address 551
Passing a Structure as an Argument .552
More on Structure Features .553
Structures or Pointer to Structures? .557
Character Arrays or Character Pointers in a Structure .558
Structure, Pointers, and malloc() 559
Compound Literals and Structures (C99) 561
Flexible Array Members (C99) .562
Functions Using an Array of Structures .565
Saving the Structure Contents in a File .566
A Structure-Saving Example 567
Program Points .570
Structures: What Next? 571
Unions: A Quick Look .572
Enumerated Types .575
enumConstants .575
Default Values .576
Assigned Values .576
enumUsage .576
Shared Namespaces .578
typedef:A Quick Look .578
Fancy Declarations .580
Functions and Pointers 582
Key Concepts .589
Summary .589
Review Questions .590
Programming Exercises 593
Trang 15C H A P T E R 1 5 Bit Fiddling .597
Binary Numbers, Bits, and Bytes 597
Binary Integers 598
Signed Integers .599
Binary Floating Point .599
Other Number Bases .600
Octal .600
Hexadecimal .601
C’s Bitwise Operators .602
Bitwise Logical Operators 602
Usage: Masks .604
Usage: Turning Bits On .605
Usage: Turning Bits Off .605
Usage: Toggling Bits .606
Usage: Checking the Value of a Bit .606
Bitwise Shift Operators .606
Programming Example 608
Another Example .610
Bit Fields .612
Bit-Field Example .614
Bit Fields and Bitwise Operators .617
Key Concepts .624
Summary .624
Review Questions .625
Programming Exercises 627
C H A P T E R 1 6 The C Preprocessor and the C Library .629
First Steps in Translating a Program .630
Manifest Constants: #define 630
Tokens .634
Redefining Constants .635
Using Arguments with #define 635
Creating Strings from Macro Arguments: The #Operator 638
Preprocessor Glue: The ##Operator .639
Variadic Macros: and_ _VA_ARGS_ _ 640
Macro or Function? .641
File Inclusion: #include 642
Header Files: An Example .643
Uses for Header Files .646
Other Directives .647
The#undefDirective .647
Being Defined—The C Preprocessor Perspective .647
Trang 16Conditional Compilation .648
Predefined Macros .653
#lineand#error 654
#pragma 654
Inline Functions .655
The C Library .658
Gaining Access to the C Library .658
Using the Library Descriptions 659
The Math Library .660
The General Utilities Library 663
Theexit()andatexit()Functions 663
Theqsort()Function .665
The Assert Library .670
memcpy()andmemmove()from the string.hLibrary .672
Variable Arguments: stdarg.h 674
Key Concepts .676
Summary .677
Review Questions .677
Programming Exercises 678
C H A P T E R 1 7 Advanced Data Representation .681
Exploring Data Representation .682
Beyond the Array to the Linked List .684
Using a Linked List .687
Afterthoughts 691
Abstract Data Types (ADTs) .692
Getting Abstract .693
Building an Interface .694
Using the Interface 699
Implementing the Interface .701
Getting Queued with an ADT .708
Defining the Queue Abstract Data Type .708
Defining an Interface .709
Implementing the Interface Data Representation .710
Testing the Queue .719
Simulating with a Queue .721
The Linked List Versus the Array .726
Binary Search Trees 730
A Binary Tree ADT .731
The Binary Search Tree Interface .732
The Binary Tree Implementation .734
Trang 17Trying the Tree 750
Tree Thoughts .754
Other Directions 756
Key Concepts .756
Summary .757
Review Questions .757
Programming Exercises 758
A P P E N D I X A Answers to the Review Quesions .759
Answers to Review Questions for Chapter 1 .759
Answers to Review Questions for Chapter 2 .760
Answers to Review Questions for Chapter 3 .761
Answers to Review Questions for Chapter 4 .764
Answers to Review Questions for Chapter 5 .767
Answers to Review Questions for Chapter 6 .770
Answers to Review Questions for Chapter 7 .773
Answers to Review Questions for Chapter 8 .776
Answers to Review Questions for Chapter 9 .777
Answers to Review Questions for Chapter 10 .779
Answers to Review Questions for Chapter 11 .782
Answers to Review Questions for Chapter 12 .785
Answers to Review Questions for Chapter 13 .786
Answers to Review Questions for Chapter 14 .789
Answers to Review Questions for Chapter 15 .792
Answers to Review Questions for Chapter 16 .793
Answers to Review Questions for Chapter 17 .795
A P P E N D I X B Reference Section 799
Section I: Additional Reading .799
Magazine .799
Online Resources .799
C Language Books .801
Programming Books 801
Reference Books 801
C++ Books .802
Section II: C Operators .802
Arithmetic Operators .803
Relational Operators .804
Assignment Operators .804
Logical Operators 805
The Conditional Operator .805
Pointer-Related Operators .806
Sign Operators .806
Trang 18Structure and Union Operators .806
Bitwise Operators 807
Miscellaneous Operators .808
Section III: Basic Types and Storage Classes .808
Summary: The Basic Data Types 808
Summary: How to Declare a Simple Variable .811
Summary: Qualifiers .812
Section IV: Expressions, Statements, and Program Flow .813
Summary: Expressions and Statements .813
Summary: The whileStatement 814
Summary: The forStatement .815
Summary: The do whileStatement .815
Summary: Using ifStatements for Making Choices .816
Summary: Multiple Choice with switch 817
Summary: Program Jumps .818
Section V: The Standard ANSI C Library with C99 Additions .819
Diagnostics:assert.h 820
Complex Numbers: complex.h(C99) .820
Character Handling: ctype.h 822
Error Reporting: errno.h 823
Floating-Point Environment: fenv.h(C99) .824
Format Conversion of Integer Types: inttypes.h(C99) .826
Localization:locale.h 827
Math Library: math.h 830
Non-Local Jumps: setjmp.h 835
Signal Handling: signal.h 836
Variable Arguments: stdarg.h 837
Boolean Support: stdbool.h(C99) .838
Common Definitions: stddef.h 838
Integer Types: stdint.h 839
Standard I/O Library: stdio.h 843
General Utilities: stdlib.h 846
String Handling: string.h 853
Type-Generic Math: tgmath.h(C99) .857
Date and Time: time.h 857
Extended Multibyte and Wide-Character Utilities: wchar.h(C99) .861
Wide Character Classification and Mapping Utilities: wctype.h(C99) 868
Section VI: Extended Integer Types 871
Exact-Width Types .872
Minimum-Width Types .872
Fastest Minimum-Width Types .873
Trang 19Maximum-Width Types .874
Integers That Can Hold Pointer Values 874
Extended Integer Constants .874
Section VII: Expanded Character Support .875
Trigraph Sequences .875
Digraphs .876
Alternative Spellings: iso646.h 876
Multibyte Characters .877
Universal Character Names (UCNs) .877
Wide Characters .878
Wide Characters and Multibyte Characters .879
Section VIII: C99 Numeric Computational Enhancements .879
The IEC Floating-Point Standard .880
Thefenv.hHeader File .880
TheSTDC FP_CONTRACTPragma 881
Additions to the math.hLibrary 881
Support for Complex Numbers .882
Section IX: Differences Between C and C++ .883
Function Prototypes 884
charConstants .884
TheconstModifier .885
Structures and Unions .886
Enumerations .886
Pointer-to-void 887
Boolean Types .887
Alternative Spellings .887
Wide-Character Support .887
Complex Types .888
Inline Functions 888
C99 Features Not Found in C++ .888
Trang 20C was a relatively little-known language when the first edition of C Primer Plus was written in
1984 Since then, the language has boomed, and many people have learned C with the help of
this book In fact, over 500,000 people have purchased C Primer Plus throughout its various
editions
As the language has grown from the early informal K&R standard through the 1990 ISO/ANSIstandard to the 1999 ISO/ANSI standard, so has this book matured through this, the fifth edi-tion As with all the editions, my aim has been to create an introduction to C that is instruc-tive, clear, and helpful
Approach and Goals
My goal is for this book to serve as a friendly, easy-to-use, self-study guide To accomplish that
objective, C Primer Plus employs the following strategies:
• Programming concepts are explained, along with details of the C language; the book
does not assume that you are a professional programmer.
• Many short, easily typed examples illustrate just one or two concepts at a time, becauselearning by doing is one of the most effective ways to master new information
• Figures and illustrations clarify concepts that are difficult to grasp in words alone
• Highlight boxes summarize the main features of C for easy reference and review
• Review questions and programming exercises at the end of each chapter allow you totest and improve your understanding of C
To gain the greatest benefit, you should take as active a role as possible in studying the topics
in this book Don’t just read the examples, enter them into your system, and try them C is avery portable language, but you may find differences between how a program works on yoursystem and how it works on ours Experiment—change part of a program to see what theeffect is Modify a program to do something slightly different Ignore the occasional warningsand see what happens when you do the wrong thing Try the questions and exercises Themore you do yourself, the more you will learn and remember
I hope that you’ll find this newest edition an enjoyable and effective introduction to the C guage
Trang 21lan-ABOUT THE AUTHOR
Stephen Prata teaches astronomy, physics, and programming at the College of Marin in
Kentfield, California He received his B.S from the California Institute of Technology and hisPh.D from the University of California, Berkeley His association with computers began withthe computer modeling of star clusters Stephen has authored or coauthored over a dozen
books, including C++ Primer Plus and Unix Primer Plus.
Trang 22With love to Vicky and Bill Prata, who, for more than 69 years, have been showing
how rewarding a marriage can be —SP
ACKNOWLEDGMENTS
I wish to thank Loretta Yates of Sams Publishing for getting this project underway and SonglinQiu of Sams Publishing for seeing it through Also, thank you Ron Liechty of Metrowerks andGreg Comeau of Comeau Computing for your help with new C99 features and your notewor-thy commitment to customer service
Trang 23WE WANT TO HEAR FROM YOU!
As the reader of this book, you are our most important critic and commentator We value your
opinion and want to know what we’re doing right, what we could do better, what areas you’dlike to see us publish in, and any other words of wisdom you’re willing to pass our way
As an associate publisher for Sams Publishing, I welcome your comments You can email orwrite me directly to let me know what you did or didn’t like about this book—as well as what
we can do to make our books better
Please note that I cannot help you with technical problems related to the topic of this book We
do have a User Services group, however, where I will forward specific technical questions related
to the book.
When you write, please be sure to include this book’s title and author as well as your name,email address, and phone number I will carefully review your comments and share them withthe author and editors who worked on the book
Email: feedback@samspublishing.comMail: Michael Stephens
Associate PublisherSams Publishing
800 East 96th StreetIndianapolis, IN 46240 USAFor more information about this book or another Sams Publishing title, visit our Web site atwww.samspublishing.com Type the ISBN (0672326965) or the title of a book in the Searchfield to find the page you’re looking for
Trang 25C H A P T E R 1
GETTING READY
You will learn about the following in this chapter:
• C’s history and features
• The steps needed to write programs
• A bit about compilers and linkers
• C standards
elcome to the world of C—a vigorous, professional programming language popularwith amateur and commercial programmers alike This chapter prepares you forlearning and using this powerful and popular language, and it introduces you to thekinds of environments in which you will most likely develop your C-legs
First, we look at C’s origin and examine some of its features, both strengths and drawbacks.Then we look at the origins of programming and examine some general principles for pro-gramming Finally, we discuss how to run C programs on some common systems
Whence C?
Dennis Ritchie of Bell Labs created C in 1972 as he and Ken Thompson worked on designingthe Unix operating system C didn’t spring full-grown from Ritchie’s head, however It camefrom Thompson’s B language, which came from… but that’s another story The importantpoint is that C was created as a tool for working programmers, so its chief goal is to be a usefullanguage
Most languages aim to be useful, but they often have other concerns The main goal for Pascal,for instance, was to provide a sound basis for teaching good programming principles BASIC,
on the other hand, was developed to resemble English so that it could be learned easily by dents unfamiliar with computers These are important goals, but they are not always compati-ble with pragmatic, workaday usefulness C’s development as a language designed for
stu-programmers, however, has made it one of the modern-day languages of choice
W
Trang 26Why C?
During the past three decades, C has become one of the most important and popular ming languages It has grown because people try it and like it In the past decade, many havemoved from C to the more ambitious C++ language, but C is still an important language in itsown right, as well a migration path to C++ As you learn C, you will recognize its many virtues(see Figure 1.1) Let’s preview a few of them now
program-FIGURE 1.1
The virtues of C
Compact code — small programs Portable to other computers
Design Features
C is a modern language incorporating the control features found desirable by the theory andpractice of computer science Its design makes it natural for top-down planning, structuredprogramming, and modular design The result is a more reliable, understandable program
Efficiency
C is an efficient language Its design takes advantage of the capabilities of current computers
C programs tend to be compact and to run quickly In fact, C exhibits some of the fine control
Trang 27usually associated with an assembly language (An assembly language is a mnemonic
represen-tation of the set of internal instructions used by a particular central processing unit design; ferent CPU families have different assembly languages.) If you choose, you can fine-tune yourprograms for maximum speed or most efficient use of memory
dif-Portability
C is a portable language, which means that C programs written on one system can be run onother systems with little or no modification If modifications are necessary, they can often bemade by simply changing a few entries in a header file accompanying the main program Mostlanguages are meant to be portable, but anyone who has converted an IBM PC BASIC program
to Apple BASIC (and they are close cousins) or has tried to run an IBM mainframe FORTRANprogram on a Unix system knows that porting is troublesome at best C is a leader in portabil-ity C compilers (programs that convert your C code into the instructions a computer usesinternally) are available for about 40 systems, running from 8-bit microprocessors to Craysupercomputers Note, however, that the portions of a program written specifically to accessparticular hardware devices, such as a display monitor, or special features of an operating sys-tem, such as Windows XP or OS X, typically are not portable
Because of C’s close ties with Unix, Unix systems typically come with a C compiler as part ofthe packages Linux installations also usually include a C compiler Several C compilers areavailable for personal computers, including PCs running various versions of Windows, andMacintoshes So whether you are using a home computer, a professional workstation, or amainframe, the chances are good that you can get a C compiler for your particular system
Power and Flexibility
C is powerful and flexible (two favorite words in computer literature) For example, most ofthe powerful, flexible Unix operating system is written in C Many compilers and interpretersfor other languages—such as FORTRAN, Perl, Python, Pascal, LISP, Logo, and BASIC—havebeen written in C As a result, when you use FORTRAN on a Unix machine, ultimately a Cprogram has done the work of producing the final executable program C programs have beenused for solving physics and engineering problems and even for animating special effects for
movies such as Gladiator.
Programmer Oriented
C is oriented to fulfill the needs of programmers It gives you access to hardware, and itenables you to manipulate individual bits in memory It has a rich selection of operators thatallows you to express yourself succinctly C is less strict than, say, Pascal in limiting what youcan do This flexibility is both an advantage and a danger The advantage is that many tasks,such as converting forms of data, are much simpler in C The danger is that with C, you canmake mistakes that are impossible in some languages C gives you more freedom, but it alsoputs more responsibility on you
Also, most C implementations have a large library of useful C functions These functions dealwith many needs that a programmer commonly faces
Trang 28C does have some faults Often, as with people, faults and virtues are opposite sides of thesame feature For example, we’ve mentioned that C’s freedom of expression also requiresadded responsibility C’s use of pointers (something you can look forward to learning about inthis book), in particular, means that you can make programming errors that are very difficult
to trace As one computer preliterate once commented, the price of liberty is eternal vigilance.C’s conciseness combined with its wealth of operators make it possible to prepare code that isextremely difficult to follow You aren’t compelled to write obscure code, but the opportunity
is there After all, what other language has a yearly Obfuscated Code contest?
There are more virtues and, undoubtedly, a few more faults Rather than delve further into thematter, let’s move on to a new topic
Whither C?
By the early 1980s, C was already a dominant language in the minicomputer world of Unixsystems Since then, it has spread to personal computers (microcomputers) and to mainframes(the big guys) See Figure 1.2 Many software houses use C as the preferred language for pro-ducing word processing programs, spreadsheets, compilers, and other products These compa-nies know that C produces compact and efficient programs More important, they know thatthese programs will be easy to modify and easy to adapt to new models of computers
FIGURE 1.2
Where C is used
C language
UNIX operating system
computer games
embedded systems
computer languages
robot factories
Lucas film
PC applications
Star Wars
Trang 29What’s good for companies and C veterans is good for other users, too More and more puter users have turned to C to secure its advantages for themselves You don’t have to be acomputer professional to use C.
com-In the 1990s, many software houses began turning to the C++ language for large programming
projects C++ grafts object-oriented programming tools to the C language (Object-oriented
programming is a philosophy that attempts to mold the language to fit a problem instead of
molding the problem to fit the language.) C++ is nearly a superset of C, meaning that any Cprogram is, or nearly is, a valid C++ program, too By learning C, you also learn much of C++.Despite the popularity of newer languages, such as C++ and Java, C remains a core skill in thesoftware business, typically ranking in the top 10 of desired skills In particular, C has becomepopular for programming embedded systems That is, it’s used to program the increasinglycommon microprocessors found in automobiles, cameras, DVD players, and other modernconveniences Also, C has been making inroads in FORTRAN’s long dominance of scientificprogramming Finally, as befits a language created to develop an operating system, it plays astrong role in the development of Linux Thus, the first decade of the twenty-first centuryfinds C still going strong
In short, C is one of the most important programming languages and will continue to be so Ifyou want a job writing software, one of the first questions you should be able to answer yes to
is “Oh say, can you C?”
What Computers Do
Now that you are about to learn how to program in C, you probably should know a littleabout how computers work This knowledge will help you understand the connectionbetween writing a program in C and what eventually takes place when you run that program
Modern computers have several components The central processing unit, or CPU, does most
of the computing work The random access memory, or RAM, serves as a workspace to hold
programs and files The permanent memory, typically a hard disk, remembers those programsand files, even if the computer is turned off And various peripherals—such as the keyboard,mouse, and monitor—provide for communication between the computer and you The CPUprocesses your programs, so let’s concentrate on its role
The life of a CPU, at least in this simplistic account, is quite simple It fetches an instructionfrom memory and executes it It fetches the next instruction from memory and executes it, and
so on (A gigahertz CPU can do this about a billion times a second, so the CPU can lead itsboring life at a tremendous pace.) The CPU has its own small workspace, consisting of several
registers, each of which can hold a number One register holds the memory address of the next
instruction, and the CPU uses this information to fetch the next instruction After it fetches aninstruction, the CPU stores the instruction in another register and updates the first register tothe address of the next instruction The CPU has a limited repertoire of instructions (known as
the instruction set) that it understands Also, these instructions are rather specific; many of
them ask the computer to move a number from one location to another—for example, from amemory location to a register
Trang 30A couple interesting points go along with this account First, everything stored in a computer
is stored as a number Numbers are stored as numbers Characters, such as the alphabeticalcharacters you use in a text document, are stored as numbers; each character has a numericcode The instructions that a computer loads into its registers are stored as numbers; eachinstruction in the instruction set has a numeric code Second, computer programs ultimately
have to be expressed in this numeric instruction code, or what is called machine language.
One consequence of how computers work is that if you want a computer to do something,you have to feed a particular list of instructions (a program) telling it exactly what to do andhow to do it You have to create the program in a language that the computer understandsdirectly (machine language) This is a detailed, tedious, exacting task Something as simple asadding two numbers together would have to be broken down into several steps, perhapssomething like the following:
1 Copy the number in memory location 2000 to register 1
2 Copy the number in memory location 2004 to register 2
3 Add the contents of register 2 to the contents of register 1, leaving the answer in register 1
4 Copy the contents of register 1 to memory location 2008
And you would have to represent each of these instructions with a numeric code!
If writing a program in this manner sounds like something you’d like to do, you’ll be sad tolearn that the golden age of machine-language programming is long past But if you prefersomething a little more enjoyable, open your heart to high-level programming languages
High-level Computer Languages and
Compilers
High-level programming languages, such as C, simplify your programming life in several ways.First, you don’t have to express your instructions in a numeric code Second, the instructionsyou use are much closer to how you might think about a problem than they are to the detailedapproach a computer uses Rather than worry about the precise steps a particular CPU wouldhave to take to accomplish a particular task, you can express your desires on a more abstractlevel To add two numbers, for example, you might write the following:
total = mine + yours;
Seeing code like this, you have a good idea what it does; looking at the machine-languageequivalent of several instructions expressed in numeric code is much less enlightening.Unfortunately, the opposite is true for a computer; to it, the high-level instruction is incompre-
hensible gibberish This is where compilers enter the picture The compiler is a program that
translates the high-level language program into the detailed set of machine language tions the computer requires You do the high-level thinking; the compiler takes care of thetedious details
Trang 31instruc-The compiler approach has another benefit In general, each computer design has its ownunique machine language So a program written in the machine language for, say, an IntelPentium CPU means nothing to a Motorola PowerPC CPU But you can match a compiler to aparticular machine language Therefore, with the right compiler or set of compilers, you canconvert the same high-level language program to a variety of different machine-language pro-grams You solve a programming problem once, and then you let your compilers translate thesolution to a variety of machine languages.
In short, high-level languages, such as C, Java, and Pascal, describe actions in a more abstractform and aren’t tied to a particular CPU or instruction set Also, high-level languages are easier
to learn and much easier to program in than are machine languages
Using C: Seven Steps
C, as you’ve seen, is a compiled language If you are accustomed to using a compiled language,such as Pascal or FORTRAN, you will be familiar with the basic steps in putting together a Cprogram However, if your background is in an interpreted language, such as BASIC, or in agraphical interface–oriented language, such as Visual Basic, or if you have no background atall, you need to learn how to compile We’ll look at that process soon, and you’ll see that it isstraightforward and sensible First, to give you an overview of programming, let’s break downthe act of writing a C program into seven steps (see Figure 1.3) Note that this is an idealiza-tion In practice, particularly for larger projects, you would go back and forth, using what youlearned at a later step to refine an earlier step
FIGURE 1.3
The seven steps ofprogramming
Maintain and modify the program Test and debug the program Run the program
Compile
Write the code
Design the program
Define the program objectives
Trang 32Step 1: Define the Program Objectives
Naturally enough, you should start with a clear idea of what you want the program to do.Think in terms of the information your program needs, the feats of calculation and manipula-tion the program needs to do, and the information the program should report back to you Atthis level of planning, you should be thinking in general terms, not in terms of some specificcomputer language
Step 2: Design the Program
After you have a conceptual picture of what your program ought to do, you should decidehow the program will go about it What should the user interface be like? How should the pro-gram be organized? Who will the target user be? How much time do you have to complete theprogram?
You also need to decide how to represent the data in the program and, possibly, in auxiliaryfiles, as well as which methods to use to process the data When you first learn programming
in C, the choices will be simple, but as you deal with more complex situations, you’ll find thatthese decisions require more thought Choosing a good way to represent the information canoften make designing the program and processing the data much easier
Again, you should be thinking in general terms, not about specific code, but some of yourdecisions may be based on general characteristics of the language For example, a C program-mer has more options in data representation than, say, a Pascal programmer
Step 3: Write the Code
Now that you have a clear design for your program, you can begin to implement it by writingthe code That is, you translate your program design into the C language Here is where youreally have to put your knowledge of C to work You can sketch your ideas on paper, but even-tually you have to get your code into the computer The mechanics of this process depend onyour programming environment We’ll present the details for some common environments
soon In general, you use a text editor to create what is called a source code file This file
con-tains the C rendition of your program design Listing 1.1 shows an example of C source code
LISTING 1.1 Example of C Source Code
#include <stdio.h>
int main(void) {
Trang 33As part of this step, you should document your work The simplest way is to use C’s commentfacility to incorporate explanations into your source code Chapter 2, “Introducing C,” willexplain more about using comments in your code.
Step 4: Compile
The next step is to compile the source code Again, the details depend on your programmingenvironment, and we’ll look at some common environments shortly For now, let’s start with amore conceptual view of what happens
Recall that the compiler is a program whose job is to convert source code into executable code
Executable code is code in the native language, or machine language, of your computer This
language consists of detailed instructions expressed in a numeric code As you read earlier, ferent computers have different machine languages, and a C compiler translates C into a par-ticular machine language C compilers also incorporate code from C libraries into the finalprogram; the libraries contain a fund of standard routines, such as printf()andscanf(), for
dif-your use (More accurately, a program called a linker brings in the library routines, but the
compiler runs the linker for you on most systems.) The end result is an executable file ing code that the computer understands and that you can run
contain-The compiler also checks that your program is valid C If the compiler finds errors, it reportsthem to you and doesn’t produce an executable file Understanding a particular compiler’scomplaints is another skill you will pick up
Step 5: Run the Program
Traditionally, the executable file is a program you can run To run the program in many mon environments, including MS-DOS, Unix, Linux consoles, just type the name of the exe-cutable file Other environments, such as VMS on a VAX, might require a run command or
com-some other mechanism Integrated development environments (IDEs), such as those provided
for Windows and Macintosh environments, allow you to edit and execute your C programfrom within the IDE by selecting choices from a menu or by pressing special keys The result-ing program also can be run directly from the operating system by clicking or double-clickingthe filename or icon
Step 6: Test and Debug the Program
The fact that your program runs is a good sign, but it’s possible that it could run incorrectly.Consequently, you should check to see that your program does what it is supposed to do
You’ll find that some of your programs have mistakes—bugs, in computer jargon Debugging is
the process of finding and fixing program errors Making mistakes is a natural part of learning
It seems inherent to programming, so when you combine learning and programming, you hadbest prepare yourself to be reminded often of your fallibility As you become a more powerfuland subtle programmer, your errors, too, will become more powerful and subtle
You have many opportunities to err You can make a basic design error You can implementgood ideas incorrectly You can overlook unexpected input that messes up your program You
Trang 34can use C incorrectly You can make typing errors You can put parentheses in the wrong place,and so on You’ll find your own items to add to this list.
Fortunately, the situation isn’t hopeless, although there might be times when you think it is.The compiler catches many kinds of errors, and there are things you can do to help yourselftrack down the ones that the compiler doesn’t catch This book will give you debugging advice
as you go along
Step 7: Maintain and Modify the Program
When you create a program for yourself or for someone else, that program could see extensiveuse If it does, you’ll probably find reasons to make changes in it Perhaps there is a minor bug
that shows up only when someone enters a name beginning with Zz, or you might think of a
better way to do something in the program You could add a clever new feature You mightadapt the program so that it runs on a different computer system All these tasks are greatlysimplified if you document the program clearly and if you follow sound design practices
Commentary
Programming is not usually as linear as the process just described Sometimes you have to goback and forth between steps For instance, when you are writing code, you might find thatyour plan was impractical You may see a better way of doing things or, after you see how aprogram runs, you might feel motivated to change the design Documenting your work helpsyou move back and forth between levels
Most learners tend to neglect steps 1 and 2 (defining program objectives and designing theprogram) and go directly to step 3 (writing the program) The first programs you write aresimple enough that you can visualize the whole process in your head If you make a mistake,it’s easy to find As your programs grow longer and more complex, mental visualizations begin
to fail, and errors get harder to find Eventually, those who neglect the planning steps are demned to hours of lost time, confusion, and frustration as they produce ugly, dysfunctional,and abstruse programs The larger and more complex the job is, the more planning it requires.The moral here is that you should develop the habit of planning before coding Use the ancientbut honorable pen-and-pencil technology to jot down the objectives of your program and tooutline the design If you do so, you eventually will reap substantial dividends in time savedand satisfaction gained
con-Programming Mechanics
The exact steps you must follow to produce a program depend on your computer ment Because C is portable, it’s available in many environments, including Unix, Linux, MS-DOS (yes, some people still use it), Windows, and Macintosh OS There’s not enough space inthis book to cover all environments, particularly because particular products evolve, die, andare replaced
Trang 35environ-First, however, let’s look at some aspects shared by many C environments, including the five
we just mentioned You don’t really need to know what follows to run a C program, but it isgood background It can also help you understand why you have to go through some particu-lar steps to get a C program
When you write a program in the C language, you store what you write in a text file called a
source code file Most C systems, including the ones we mentioned, require that the name of
the file end in.c(for example, wordcount.candbudget.c) The part of the name before the
period is called the basename, and the part after the period is called the extension Therefore,
budgetis a basename and cis the extension The combination budget.cis the filename Thename should also satisfy the requirements of the particular computer operating system Forexample, MS-DOS is an operating systems for IBM PCs and clones It requires that the base-name be no more than eight characters long, so the wordcount.cfilename mentioned earlierwould not be a valid DOS filename Some Unix systems place a 14-character limit on thewhole name, including the extension; other Unix systems allow longer names, up to 255 char-acters Linux, Windows, and the Macintosh OS also allow long names
So that we’ll have something concrete to refer to, let’s assume we have a source file called concrete.ccontaining the C source code in Listing 1.2
LISTING 1.2 Theconcrete.cProgram
#include <stdio.h>
int main(void) {
printf(“Concrete contains gravel and cement.\n”);
return 0;
}Don’t worry about the details of the source code file shown in Listing 1.2; you’ll learn aboutthem in Chapter 2
Object Code Files, Executable Files, and Libraries
The basic strategy in C programming is to use programs that convert your source code file to
an executable file, which is a file containing ready-to-run machine language code C mentations do this in two steps: compiling and linking The compiler converts your sourcecode to an intermediate code, and the linker combines this with other code to produce theexecutable file C uses this two-part approach to facilitate the modularization of programs Youcan compile individual modules separately and then use the linker to combine the compiledmodules later That way, if you need to change one module, you don’t have to recompile theother ones Also, the linker combines your program with precompiled library code
imple-There are several choices for the form of the intermediate files The most prevalent choice, andthe one taken by the implementations described here, is to convert the source code to machine
language code, placing the result in an object code file, or object file for short (This assumes
Trang 36that your source code consists of a single file.) Although the object file contains machine guage code, it is not ready to run The object file contains the translation of your source code,but it is not yet a complete program.
lan-The first element missing from the object code file is something called startup code, which is
code that acts as an interface between your program and the operating system For example,you can run an IBM PC compatible under DOS or under Linux The hardware is the same ineither case, so the same object code would work with both, but you would need differentstartup code for DOS than you would for Linux because these systems handle programs differ-ently from one another
The second missing element is the code for library routines Nearly all C programs make use of
routines (called functions) that are part of the standard C library For example, concrete.cuses the function printf() The object code file does not contain the code for this function; itmerely contains instructions saying to use the printf()function The actual code is stored in
another file, called a library A library file contains object code for many functions.
The role of the linker is to bring together these three elements—your object code, the standardstartup code for your system, and the library code—and put them together into a single file,the executable file For library code, the linker extracts only the code needed for the functionsyou use from the library (see Figure 1.4)
Trang 37On some systems, you must run the compile and link programs separately On other systems,the compiler starts the linker automatically, so you have to give only the compile command.Now let’s look at some specific systems.
Unix System
Because C’s popularity began on Unix systems, we will start there
Editing on a Unix System
Unix C does not have its own editor Instead, you use one of the general-purpose Unix editors,such as emacs, jove, vi, or an X Window System text editor
Your two main responsibilities are typing the program correctly and choosing a name for thefile that will store the program As discussed, the name should end with .c Note that Unixdistinguishes between uppercase and lowercase Therefore, budget.c,BUDGET.c, andBudget.care three distinct and valid names for C source files, but BUDGET.Cis not a validname because it uses an uppercase Cinstead of a lowercase c
Using the vi editor, we prepared the following program and stored it in a file called inform.c
#include <stdio.h>
int main(void) {
printf(“A c is used to end a C program filename.\n”);
return 0;
}This text is the source code, and inform.cis the source file The important point here is thatthe source file is the beginning of a process, not the end
Compiling on a Unix System
Our program, although undeniably brilliant, is still gibberish to a computer A computer doesn’t understand things such as #includeandprintf (At this point, you probably don’teither, but you will soon learn, whereas the computer won’t.) As we discussed earlier, we needthe help of a compiler to translate our code (source code) to the computer’s code (machinecode) The result of these efforts will be the executable file, which contains all the machinecode that the computer needs to get the job done
The Unix C compiler is called cc To compile the inform.cprogram, you need to type the lowing:
fol-cc inform.cAfter a few seconds, the Unix prompt will return, telling you that the deed is done You mightget warnings and error messages if you failed to write the program properly, but let’s assumeyou did everything right (If the compiler complains about the word void, your system has notyet updated to an ANSI C compiler We’ll talk more about standards soon Meanwhile, justdelete the word voidfrom the example.) If you use the lscommand to list your files, you will
Trang 38find that there is a new file called a.out(see Figure 1.5) This is the executable file containingthe translation (or compilation) of the program To run it, just type
a.outand wisdom pours forth:
A c is used to end a C program filename.
If you want to keep the executable file (a.out), you should rename it Otherwise, the file isreplaced by a new a.outthe next time you compile a program
Compiler
executable code
run program by typing filename a.out
Text Editor
What about the object code? The cc compiler creates an object code file having the same name as the source code, but with an .oextension In our example, the object code file iscalledinform.o, but you won’t find it, because the linker removes it once the executable pro-gram has been completed However, if the original program used more than one source codefile, the object code files would be saved When we discuss multiple-file programs later in thetext, you will see that this is a fine idea
base-Linux System
Linux is a popular open-source, Unix-like operating system that runs on a variety of platforms,including IBM compatibles and Macintoshes Preparing C programs on Linux is much the
Trang 39same as for Unix systems, except that you would use the public domain C compiler, called gcc,
that’s provided by GNU The compile command would look like this:
gcc inform.cNote that installing gcc may be optional when installing Linux, so you (or someone) mighthave to install gcc if it wasn’t installed earlier Typically, the installation makes cc an alias forgcc, so you can use cc in the command line instead of gcc if you like
You can obtain further information about gcc, including information about new releases, athttp://www.gnu.org/software/gcc/gcc.html
Integrated Development Environments (Windows)
C compilers are not part of the standard Windows package, so you may need to obtain andinstall a C compiler Quite a few vendors, including Microsoft, Borland, Metrowerks, and
Digital Mars, offer Windows-based integrated development environments, or IDEs (These
days, most are combined C and C++ compilers.) All have fast, integrated environments forputting together C programs The key point is that each of these programs has a built-in editoryou can use to write a C program Each provides menus that enable you to name and saveyour source code file, as well as menus that allow you to compile and run your program with-out leaving the IDE Each dumps you back into the editor if the compiler finds any errors, andeach identifies the offending lines and matches them to the appropriate error messages
The Windows IDEs can be a little intimidating at first because they offer a variety of targets—
that is, a variety of environments in which the program will be used For example, they mightgive you a choice of 16-bit Windows programs, 32-bit Windows programs, dynamic linklibrary files (DLLs), and so on Many of the targets involve bringing in support for the
Windows graphical interface To manage these (and other) choices, you typically create a
pro-ject to which you then add the names of the source code files you’ll be using The precise steps
depend on the product you use Typically, you first use the File menu or Project menu to ate a project What’s important is choosing the correct form of project The examples in thisbook are generic examples designed to run in a simple command-line environment The vari-ous Windows IDEs provide one or more choices to match this undemanding assumption
cre-Microsoft Visual C 7.1, for example, offers the Win32 Console Application option ForMetrowerks CodeWarrior 9.0, choose Win32 C Stationery and then select C Console App orthe WinSIOUX C App (the latter has a nicer user interface) For other systems, look for anoption using terms such as DOS EXE, Console, or Character Mode executable These modeswill run your executable program in a console-like window After you have the correct projecttype, use the IDE menu to open a new source code file For most products, you can do this byusing the File menu You may have to take additional steps to add the source file to theproject
Because the Windows IDEs typically handle both C and C++, you need to indicate that youwant a C program With some products, such as Metrowerks CodeWarrior, you use the projecttype to indicate that you want to use C With other products, such as Microsoft Visual C++,you use the .cfile extension to indicate that you want to use C rather than C++ However,
Trang 40most C programs also work as C++ programs Reference Section IX, “Differences Between Cand C++,” compares C and C++.
One problem you might encounter is that the window showing the program execution ishes when the program terminates If that is the case for you, you can make the programpause until you press the Enter key To do that, add the following line to the end of the pro-gram, just before the returnstatement:
van-getchar();
This line reads a keystroke, so the program will pause until you press the Enter key
Sometimes, depending on how the program functions, there might already be a keystrokewaiting In that case, you’ll have to usegetchar() twice:
getchar();
getchar();
For example, if the last thing the program did was ask you to enter your weight, you wouldhave typed your weight and then pressed the Enter key to enter the data The program wouldread the weight, the first getchar()would read the Enter key, and the second getchar()would cause the program to pause until you press Enter again If this doesn’t make a lot ofsense to you now, it will after you learn more about C input
Although the various IDEs have many broad principles in common, the details vary fromproduct to product and, within a product line, from version to version You’ll have to do someexperimenting to learn how your compiler works You might even have to read the manual ortry an online tutorial
DOS Compilers for the IBM PC
For many, running DOS on a PC is out of fashion these days, but it is still an option for thosewith limited computer resources and a modest budget and for those who prefer a simpleroperating system without the bells, whistles, and distractions of a windowing environment.Many Windows IDEs additionally provide command-line tools, allowing you to program inthe DOS command-line environment The Comeau C/C++ compiler that is available on manysystems, including several Unix and Linux variants, has a command-line DOS version Also,there are freeware and shareware C compilers that work under DOS For example, there is aDOS-based version of the GNU gcc compiler
Source code files should be text files, not word processor files (Word processor files contain alot of additional information about fonts and formatting.) You should use a text editor, such asWindows Notepad, or the EDIT program that comes with some versions of DOS You can use
a word processor, if you use the Save As feature to save the file in text mode The file shouldhave a .cextension Some word processors automatically add a .txtextension to text files Ifthis happens to you, you need to change the filename, replacing txtwithc
C compilers for the PC typically, but not always, produce intermediate object code files having
an.objextension Unlike Unix compilers, C compilers typically don’t remove these files whendone Some compilers produce assembly language files with .asmextensions or use some spe-cial format of their own