C Primer Plus, Fourth EditionBy Stephen Prata Table of Contents... C Primer Plus, Fourth EditionBy Stephen Prata Table of Contents... C Primer Plus, Fourth EditionBy Stephen Prata Table
Trang 1Publisher : Sams Publishing Pub Date : September 19, 2001 ISBN : 0-672-32222-6
Trang 2The for Loop
More Assignment Operators: +=, -=, *=, /=, %=
Trang 3Adding else to the if Statement
Let's Get Logical
A Word-Count Program
The Conditional Operator: ?
Loop Aids: continue and break
Multiple Choice: switch and break
The goto Statement
Altering Variables in the Calling Function
Pointers: A First Look
Trang 5Communicating with Files
Standard I/O
A Simple-Minded File-Condensing Program
File I/O: fprintf() , fscanf() , fgets() , and fputs()
Adventures in Random Access: fseek() and ftell()
Manifest Constants: #define
Using Arguments with #define
Trang 7Index
Top
Trang 8
C Primer Plus, Fourth EditionBy Stephen Prata Table of Contents
Trang 9Copyright © 2002 by Sams Publishing
All rights reserved No part of this book shall bereproduced, stored in a retrieval system, or
transmitted by any means, electronic, mechanical,photocopying, recording, or otherwise, without
written permission from the publisher No patentliability is assumed with respect to the use of theinformation contained herein Although every
precaution has been taken in the preparation of thisbook, the publisher and author assume no
responsibility for errors or omissions Nor is anyliability assumed for damages resulting from the use
Trang 10All terms mentioned in this book that are known to betrademarks or service marks have been appropriatelycapitalized Sams Publishing cannot attest to the
accuracy of this information Use of a term in this
book should not be regarded as affecting the validity
of any trademark or service mark
Apple is a registered trademark of Apple Computer,Inc
Borland C++ is a registered trademark of Borland
International, Inc
CodeWarrior is a registered trademark of Metrowerks,Inc
Cray is a registered trademark of Cray Computer, Inc
IBM and PC are registered trademarks and PC DOS is
a trademark of the International Business MachinesCompany
Macintosh is a registered trademark of Macintosh
Laboratory, Inc., licensed by Apple Computer, Inc.Microsoft and MS-DOS are registered trademarks of
Trang 11International Corporation
Warning and Disclaimer
Trang 12
complete and as accurate as possible, but no warranty
or fitness is implied The information provided is on
an "as is" basis The author and the publisher shallhave neither liability nor responsibility to any person
or entity with respect to any loss or damages arisingfrom the information contained in this book or fromthe use of the Web site or programs accompanying it
Trang 15
C Primer Plus, Fourth EditionBy Stephen Prata Table of Contents
Trang 16
Top
Trang 17
Figures and illustrations clarify concepts that are
difficult to grasp in words alone
Highlight boxes summarize the main features of Cfor easy reference and review
Trang 18
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 a very portable language,but you may find differences between how a programworks on your system and how it works on ours
Experimentchange part of a program to see what theeffect is Modify a program to do something slightlydifferent Ignore the occasional warnings and see whathappens when you do the wrong thing Try the
questions and exercises The more you do yourself,the more you will learn and remember
I hope that you'll find this newest edition an enjoyableand effective introduction to the C language
Top
Trang 19C99 It was adopted by the International Organizationfor Standardization (ISO) and the International
Expanded character support
Boolean support
Variable-length arrays
Trang 20
consolidated and expanded, and Chapter 12, "StorageClasses, Linkage, and Memory Management,"
incorporates dynamic memory allocation into the
discussion of C storage classes and memory
management Numerous other changes and additionshave been incorporated in response to reader requests
to make this edition an even more effective learningtool
Top
Trang 21
C Primer Plus, Fourth EditionBy Stephen Prata Table of Contents
Trang 22Stephen Prata is a professor of physics and
astronomy at the College of Marin in Kentfield,
California, where he teaches astronomy, physics, andprogramming He received his B.S from the
California Institute of Technology and his Ph.D fromthe University of California, Berkeley His associationwith computers began with the computer modeling ofstar clusters Stephen has authored or coauthored over
a dozen books, including C++ Primer Plus and Unix Primer Plus.
Top
Trang 23
C Primer Plus, Fourth EditionBy Stephen Prata Table of Contents
Trang 25
C Primer Plus, Fourth EditionBy Stephen Prata Table of Contents
Trang 26welcome your comments You can fax, email, or write
me directly to let me know what you did or didn't likeabout this bookas well as what we can do to make ourbooks stronger
share them with the author and editors who worked on
Trang 27
Top
Trang 28
C Primer Plus, Fourth EditionBy Stephen Prata Table of Contents
Trang 30
Top
Trang 31Most 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 belearned easily by students unfamiliar with computers.These are important goals, but they are not always
compatible with pragmatic, workaday usefulness C'sdevelopment as a language designed for
Trang 32
modern-day languages of choice
Top
Trang 33
C Primer Plus, Fourth EditionBy Stephen Prata Table of Contents
Chapter 1 Getting Ready
Why C?
During the past three decades, C has become one ofthe most important and popular programming
languages It has grown because people try it and like
it In the past decade, many have moved from C to themore ambitious C++ language, but C is still an
Trang 34C is a modern language incorporating the control
features found desirable by the theory and practice ofcomputer science Its design makes it natural for users
to use top-down planning, structured programming,and modular design The result is a more reliable,
understandable program
Efficiency
Trang 36of an operating system¡ªsuch as Windows or OS
X¡ªtypically are not portable
Because of C's close ties with UNIX, UNIX systemstypically come with a C compiler as part of the
packages Linux installations also usually include a Ccompiler Several C compilers are available for
personal computers, including PCs running variousversions of Windows and Macintoshes So whetheryou are using a home computer, a professional
workstation, or a mainframe, the chances are goodthat you can get a C compiler for your particular
result, when you use FORTRAN on a UNIX machine,ultimately a C program has done the work of
producing the final executable program C programshave been used for solving physics and engineering
Trang 37movies such as Gladiator.
Programmer Oriented
C is oriented to fulfill the needs of programmers Itgives you access to hardware, and it enables you tomanipulate individual bits in memory It has a richselection of operators that allow you to express
yourself succinctly C is less strict than, say, Pascal, inlimiting what you can do This flexibility is both anadvantage and a danger The advantage is that manytasks, such as converting forms of data, are much
simpler in C The danger is that with C, you can makemistakes that are impossible in some languages Cgives you more freedom, but it also puts more
responsibility on you
Also, most C implementations have a large library ofuseful C functions These functions deal with manyneeds that a programmer commonly faces
Shortcomings
C does have some faults Often, as with people, faultsand virtues are opposite sides of the same feature Forexample, we've mentioned that C's freedom of
Trang 38of pointers (something you can look forward to
learning about in this book), in particular, means thatyou can make programming errors that are very
difficult to trace As one computer preliterate oncecommented, the price of liberty is eternal vigilance
C's conciseness combined with its wealth of operatorsmake it possible to prepare code that is extremely
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 Codecontest?
There are more virtues and, undoubtedly, a few morefaults Rather than delve further into the matter, let'smove on to a new topic
Top
Trang 39
C Primer Plus, Fourth EditionBy Stephen Prata Table of Contents
C as the preferred language for producing word
processing programs, spreadsheets, compilers, andother products These companies know that C
Trang 40What's good for companies and C veterans is good forother users, too More and more computer users haveturned to C to secure its advantages for themselves.
Trang 41Despite the popularity of newer languages, such asC++ and Java, C remains a core skill in the softwarebusiness, typically ranking in the top ten of desiredskills In particular, C has become popular for
programming embedded systems That is, it's used toprogram the increasingly common microprocessorsfound in automobiles, cameras, DVD players, and
other modern conveniences Also, C has been makinginroads in FORTRAN's long dominance of scientificprogramming Finally, as befits a language created todevelop an operating system, it plays a strong role inthe development of Linux Thus, the first decade ofthe twenty-first century finds C still going strong
In short, C is one of the most important programminglanguages and will continue to be so If you want ajob writing software, one of the first questions youshould be able to answer yes to is "Oh say, can youC?"
Top
Trang 42
C Primer Plus, Fourth EditionBy Stephen Prata Table of Contents
Chapter 1 Getting Ready
What Computers Do
Now that you are about to learn how to program in C,you probably should know a little about how
computers work This knowledge will help you
understand the connection between writing a program
in C and what eventually takes place when you runthat program
Modern computers have several components Thecentral processing unit, or CPU, does most of the
computing work The random-access memory, or
RAM, serves as a workspace to hold programs andfiles The permanent memory, typically a hard disk,remembers those programs and files, even if the
computer is turned off And various peripherals¡ªsuch
as the keyboard, mouse, and monitor¡ªprovide forcommunication between the computer and you TheCPU processes your programs, so let's concentrate onits role
Trang 43and executes it It fetches the next instruction from
memory and executes it, and so on (A gigahertz CPUcan do this about a billion times a second, so the CPUcan lead its boring 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 fetchthe next instruction After it fetches an instruction, theCPU stores the instruction in another register and
Trang 44
instruction code, or what is called machine language.
One consequence of how computers work is that ifyou want a computer to do something, you have tofeed a particular list of instructions (a program) telling
it exactly what to do and how to do it You have tocreate the program in a language that the computerunderstands directly (machine language) This is adetailed, tedious, exacting task Something as simple
as adding two numbers together would have to be
broken down into several steps:
1 Copy the number in memory location 2000 to register 1.
And you would have to represent each of these
instructions with a numeric code!
Trang 45something you'd like to do, you'll be sad to learn thatthe golden age of machine-language programming islong past But if you prefer something a little moreenjoyable, open your heart to high-level programminglanguages
Top
Trang 46
C Primer Plus, Fourth EditionBy Stephen Prata Table of Contents
Chapter 1 Getting Ready
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 instructions you use aremuch closer to how you might think about a problemthan they are to the detailed approach a computer
uses Rather than worry about the precise steps a
particular CPU would have to take to accomplish aparticular task, you can express your desires on a
more abstract level To add two numbers, for
example, you might write the following:
total = mine + yours;
Seeing code like this, you have a good idea what itdoes; looking at the machine-language equivalent ofseveral instructions expressed in numeric code is
Trang 48easier to program in than are machine languages
Top
Trang 49at that process soon, and you'll see that it is straightforward andsensible First, to give you an overview of programming, let'sbreak down the act of writing a C program into seven steps (see
Figure 1.3) Note that this is an idealization In practice,
particularly for larger projects, you would go back and forth,using what you learned at a later step to refine an earlier step
Figure 1.3 The seven steps of programming.
Trang 50Naturally enough, you should start with a clear idea of what youwant the program to do Think in terms of the information yourprogram needs, the feats of calculation and manipulation theprogram needs to do, and the information the program shouldreport back to you At this level of planning, you should be
thinking in general terms, not in terms of some specific
computer language
Step 2: Design the Program
Trang 51to do, you should decide how the program will go about it
What should the user interface be like? How should the program
be organized? Who will the target user be? How much time doyou have to complete the program?
You also need to decide how to represent the data in the
program and, possibly, in auxiliary files, and which methods touse to process the data When you first learn programming in C,the choices will be simple, but as you deal with more complexsituations, you'll find that these decisions require more thought.Choosing a good way to represent the information can often
Step 3: Write the Code
Now that you have a clear design for your program, you canbegin to implement it by writing the code That is, you translateyour program design into the C language Here is where youreally have to put your knowledge of C to work You can sketch
Trang 52your programming environment We'll present the details forsome common environments soon In general, you use a text
printf("So you have %d dog(s)!\n", dogs); return 0;
Trang 53a particular machine language C compilers also incorporatecode from C libraries into the final program; the libraries
contain a fund of standard routines, such as printf() and
scanf(), for 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 executablefile containing code that the computer understands and that youcan run
The compiler also checks that your program is valid C If thecompiler finds errors, it reports them to you and doesn't produce
an executable file Understanding a particular compiler's
complaints is another skill you will pick up
Step 5: Run the Program