• Tidak ada hasil yang ditemukan

Practical C Prog Free ebook download

N/A
N/A
Protected

Academic year: 2019

Membagikan "Practical C Prog Free ebook download "

Copied!
504
0
0

Teks penuh

(1)
(2)

1

Table of Contents

Preface

How This Book is Organized Chapter by Chapter

Notes on the Third Edition Font Conventions

Obtaining Source Code Comments and Questions Acknowledgments

Acknowledgments to the Third Edition

I. Basics

1. What Is C?

How Programming Works Brief History of C How C Works

How to Learn C

2. Basics of Program Writing

Programs from Conception to Execution Creating a Real Program

Creating a Program Using a Command-Line Compiler

Creating a Program Using an Integrated Development Environment Getting Help on UNIX

Getting Help in an Integrated Development Environment IDE Cookbooks

Programming Exercises 3. Style

Common Coding Practices Coding Religion

Indentation and Code Format Clarity

Simplicity Summary

4. Basic Declarations and Expressions Elements of a Program

Basic Program Structure Simple Expressions Variables and Storage

(3)

Variable Declarations Integers

Assignment Statements printf Function

Floating Point

Floating Point Versus Integer Divide Characters

Answers

Programming Exercises

5. Arrays, Qualifiers, and Reading Numbers Arrays

Strings

Reading Strings

Multidimensional Arrays Reading Numbers

Initializing Variables Types of Integers Types of Floats Constant Declarations

Hexadecimal and Octal Constants Operators for Performing Shortcuts Side Effects

++x or x++

More Side-Effect Problems Answers

Programming Exercises

6. Decision and Control Statements

if Statement else Statement

How Not to Use strcmp Looping Statements while Statement break Statement continue Statement

Assignment Anywhere Side Effect Answer

Programming Exercises 7. Programming Process

(4)

3

Code Design Prototype Makefile Testing Debugging Maintenance Revisions

Electronic Archaeology Marking Up the Program Using the Debugger Text Editor as a Browser Add Comments

Programming Exercises

II. Simple Programming

8. More Control Statements for Statement switch Statement

switch, break, and continue Answers

Programming Exercises 9. Variable Scope and Functions Scope and Class

Functions

Functions with No Parameters Structured Programming Recursion

Answers

Programming Exercises 10. C Preprocessor

#define Statement Conditional Compilation include Files

Parameterized Macros Advanced Features Summary

Answers

Programming Exercises 11. Bit Operations

Bit Operators

The and Operator (&)

(5)

Bitwise or (|)

The Bitwise Exclusive or (^)

The Ones Complement Operator (Not) (~) The Left- and Right-Shift Operators (<<, >>) Setting, Clearing, and Testing Bits

Bitmapped Graphics Answers

Programming Exercises 12. Advanced Types

Structures Unions typedef enum Type Casting

Bit Fields or Packed Structures Arrays of Structures

Summary

Programming Exercises 13. Simple Pointers

Pointers as Function Arguments const Pointers

Pointers and Arrays How Not to Use Pointers

Using Pointers to Split a String Pointers and Structures

Command-Line Arguments Programming Exercises Answers

14. File Input/Output Conversion Routines Binary and ASCII Files The End-of-Line Puzzle Binary I/O

Buffering Problems Unbuffered I/O

Designing File Formats Answers

Programming Exercises 15. Debugging and Optimization Debugging

(6)

5

Debugging a Binary Search Runtime Errors

The Confessional Method of Debugging Optimization

Answers

Programming Exercises 16. Floating Point

Floating-Point Format

Floating Addition/Subtraction Multiplication

Division

Overflow and Underflow Roundoff Error

Accuracy

Minimizing Roundoff Error Determining Accuracy Precision and Speed Power Series

Programming Exercises

III. Advanced Programming Concepts

17. Advanced Pointers

Pointers and Structures free Function

Linked List

Structure Pointer Operator Ordered Linked Lists Double-Linked Lists Trees

Printing a Tree Rest of Program

Data Structures for a Chess Program Answers

Programming Exercises 18. Modular Programming Modules

Public and Private The extern Modifier Headers

The Body of the Module

A Program to Use Infinite Arrays

(7)

The Makefile for Multiple Files Using the Infinite Array

Dividing a Task into Modules

Module Division Example: Text Editor Compiler

Spreadsheet

Module Design Guidelines Programming Exercises 19. Ancient Compilers

K&R-Style Functions Library Changes Missing Features Free/Malloc Changes lint

Answers

20. Portability Problems Modularity

Word Size

Byte Order Problem Alignment Problem NULL Pointer Problem Filename Problems File Types

Summary Answers

21. C's Dustier Corners do/while

goto

The ?: Construct The , Operator volatile Qualifier Answer

22. Putting It All Together Requirements

Specification Code Design Coding

(8)

7

Expandability Testing

Revisions

A Final Warning Program Files

Programming Exercises 23. Programming Adages General

Design Declarations switch Statement Preprocessor Style

Compiling Final Note Answer

IV. Other Language Features

A. ASCII Table

B. Ranges and Parameter Passing Conversions C. Operator Precedence Rules

D. A Program to Compute a Sine Using a Power Series Glossary

Index

(9)

Pr e fa ce

This book is devot ed t o pr act ical C pr ogr am m ing. C is cur r ent ly t he

prem ier language for soft w are developers. That 's because it 's w idely

dist r ibut ed and st andar d. New er languages ar e available, such as

C+ + , but t hese are st ill evolving. C is st ill t he language of choice for

robust , port able program m ing.

This book em phasizes t he skills you w ill need t o do real- w or ld

program m ing. I t t eaches you not only t h e m echanics of t he C

language, but t he ent ir e life cy cle of a C pr ogr am as w ell ( including t he

program 's concept ion, design, code, m et hods, debugging, release,

docum ent at ion, m aint enance, and revision) .

Good st yle is em phasized. To cr eat e a good pr ogr am yo u m ust do

m or e t han j ust t y pe in code. I t is an ar t in w hich w r it ing and

program m ing skills blend t hem selves t oget her t o form a m ast erpiece.

Tr ue ar t can be cr eat ed. A w ell-w r it t en pr ogr am not only funct ions

correct ly, but is sim ple and easy t o underst and. Com m ent s allow t he

program m er t o include descript ive t ext inside t he program . When

clear ly w r it t en, a com m ent ed pr ogr am is highly pr ized.

A pr ogr am should be as sim ple as possible. A pr ogr am m er should

avoid clever t r icks. This book st r esses sim ple, pr act ical rules. For

exam ple, t her e ar e 15 oper at or pr ecedence r ules in C. These can be

sim plified int o t wo rules:

1 .

Mult iply and div ide com e befor e add and subt r act .

2 .

Put parent heses around everyt hing else.

Consider t w o pr ogr am s. One w as w r it t en by a clev er pr ogr am m er

using all t he t r icks. The pr ogr am cont ains no com m ent s, but it w or ks.

The ot her program is w ell com m ent ed and nicely st ruct ured, but it

doesn't work. Which program is m ore useful? I n t he long run, t he

broken one. I t can be fixed. Alt hough t he clever p rogram works now,

sooner or lat er all pr ogr am s hav e t o be m odified. The w or st t hing t hat

y ou w ill ev er hav e t o do is t o m odify a clev er ly w r it t en pr ogr am .

(10)

9

k now how t o use t he basic funct ions such as a t ex t edit or and t he

filesy st em .

Specific inst ruct ions are given for producing and running program s

using t he UN I X operat ing syst em wit h a generic

cc

com piler or t he

Fr ee Soft w ar e Foundat ion's

gcc

com piler . For MS- DOS/ Windows users,

inst ruct ions are included for Borland C+ + , Turbo C+ + , and Microsoft

Visual C+ + . ( These com pilers com pile bot h C and C+ + code.) The

book also gives exam ples of using t he pr ogr am m ing ut ilit y

m ake

f or

aut om at ed program product ion.

H ow Th is Book is Or g a n iz e d

You m ust cr aw l befor e y ou w alk . I n Part I w e t each y ou h ow t o crawl.

These chapt er s enable y ou t o w r it e v er y sim ple pr ogr am s. We st ar t

w it h t he m echanics of program m ing and program m ing st yle. Next ,

y ou lear n how t o use v ar iables and v er y sim ple decision and cont r ol

st at em ent s. I n Chapt er 7 , w e t ak e y ou on a com plet e t our of t he

soft w ar e life cy cle t o show y ou how r eal pr ogr am s ar e cr eat ed.

Part I I describes all of t he o t her sim ple st at em ent s and oper at or s t hat

ar e used in pr ogr am m ing. You'll also lear n how t o or ganize t hese

st at em ent s int o sim ple funct ions.

I n Par t I I I w e t ak e our basic declar at ions and st at em ent s and lear n

how t hey can be used in t he const r uct ion of adv anced t y pes such as

st r uct ur es, unions, and classes. We'll also int r oduce t he concept of

point er s. Finally, a num ber of m iscellaneous feat ur es ar e descr ibed

Part I V .

Ch a p t e r b y Ch a p t e r

Chapt er 1 giv es a br ief descr ipt ion of t h e C lan gu age an d it s u se. Th is ch apt er in clu des som e back grou n d on t h e h ist or y of t h e lan g u ag e.

Chapt er 2 ex plain s t h e basic pr ogr am m in g pr ocess an d giv es y ou en ou gh infor m at ion t o w r it e a v er y sim ple pr ogr am .

Chapt er 3 discusses pr ogr am m ing st y le. Com m ent ing a pr ogr am is cov er ed, as w ell as w r it in g clear an d sim ple code.

(11)

Chapt er 4 in t r odu ces you t o sim p le C st at em en t s. Basic v ar iab les an d t h e

assign m en t st at em en t ar e cov er ed in det ail, alon g w it h ar it h m et ic oper at or s + , - , * , / , and % .

Chapt er 5 cov er s ar r ay s and m or e co m plex v ar iables. Shor t hand oper at or s such as + + an d % = ar e also descr ibed.

Chapt er 6 ex plains sim ple decision st at em ent s including if , e lse , a n d for. A discussion of = = v er sus = is p r esen t ed .

Chapt er 7 t ak es y ou t h r ou gh all t h e n ecessar y st eps t o cr eat e a sim ple pr ogr am fr om specificat ion t hr ough r elease. St r uct ur ed pr ogr am m ing, fast pr ot ot y ping, and debugging ar e also discu ssed.

Chapt er 8 descr ibes addit ional cont r ol st at em ent s. I ncluded ar e w h ile , b r e a k , an d

con t in u e . Th e sw it ch st at em en t is discu ssed in det ail.

Chapt er 9 int r oduces local v ar iables, funct ions, and par am et er s.

Chapt er 1 0 descr ibes t h e C pr epr ocessor , w h ich giv es t h e pr og r am m er t r em endous flex ibilit y in w r it ing code. The chapt er also pr ov ides t he pr ogr am m er w it h a t r em en dou s n u m ber of w ay s t o m ess u p. Sim ple r u les t h at h elp k eep t h e pr epr ocessor fr om becom in g a pr oblem ar e descr ibed.

Ch ap t er 1 1 discu sses t h e logical C oper at or s t h at w or k on bit s.

Chapt er 1 2 ex plain s st r u ct u r es an d ot h er adv an ced t y pes. Th e siz e of oper at or an d t h e e n u m t y pe ar e in clu ded.

Ch ap t er 1 3 in t r odu ces C poin t er v ar iables an d sh ow s som e of t h eir u ses.

Ch ap t er 1 4 descr ibes bot h buffer ed and unbuffer ed input / out put . ASCI I and binar y f iles ar e d iscu ssed , an d y ou ar e sh ow n h ow t o con st r u ct a sim p le f ile.

Chapt er 1 5 descr ibes h ow t o de bu g a pr ogr am , as w ell as h ow t o u se an in t er act iv e debu gger . You ar e sh ow n n ot on ly h ow t o debu g a pr ogr am , bu t also h ow t o w r it e a pr ogr am so t hat it is easy t o debug. This chapt er also descr ibes m any opt im izat ion t ech n iqu es f or m ak in g y ou r pr ogr am r u n fast er an d m or e efficien t ly .

Ch ap t er 1 6 u ses a sim ple decim al f loat in g-poin t f or m at t o in t r odu ce y ou t o t h e pr oblem s inher ent in float ing point , such as r oundoff er r or , pr ecision lo ss, ov er flow , an d u n der f low .

(12)

11

Ch ap t er 1 8 sh ow s h ow t o split a pr ogr am in t o sev er al f iles an d u se m odu lar pr ogr am m ing t echniques. The m a k e u t ilit y is ex plain ed in m or e det ail.

Ch ap t er 1 9 descr ibes t h e old, pr e -ANSI C lan gu age an d associat ed com piler s. Alt h ou gh su ch com piler s ar e r ar e t oday , a lot of code w as w r it t en for t h em an d t h er e ar e st ill a lar ge n u m ber of pr ogr am s ou t t h er e t h at u se t h e old sy n t ax .

Ch ap t er 2 0 descr ibes t he pr oblem s t hat can occur w hen y ou port a pr ogr am ( m ov e it f r om on e m ach in e t o an ot h er ) .

Ch ap t er 2 1 descr ibes t he do/ w h ile st at em en t , t h e , oper at or , an d t h e ? an d : oper at or s.

Chapt er 2 2 det ails t h e st eps n ecessar y t o t ak e a com plex pr ogr am fr om con cept ion t o com plet ion. I nfor mat ion -h idin g an d m odu lar pr ogr am m in g t ech n iqu es ar e em ph asized.

Ch ap t er 2 3 list s som e pr ogr am m in g adages t h at w ill h elp y ou con st r u ct good C pr ogr am s.

Appendix A list s t he oct al, hex adecim al, and decim al r epr esent at ions of t he ASCI I ch ar act er set t h at is n ow in alm ost u n iv er sal u se.

Appendix B list s t he lim it s y ou can ex pect t o com e up against in handling num ber s w it h v ar iou s sizes of m em or y allocat ion .

Appendix C list s t h ose im possible -to -r em em ber r ules, t o h elp y ou w h en y ou en cou n t er code w r it t en by r u de people w h o didn ' t u se en ou gh par en t h eses.

Appendix D , illust r at es t he m anipulat ion of float ing -poin t ( r eal) n u m ber s, w h ich did not r eceiv e com plet e at t en t ion in t h e r est of t h e book .

The Appendix A defines m any of t he t echnical t er m s used t hr oughout t he book .

Com pu t er lan gu ages ar e best lear n ed by w r it in g an d debugging pr ogr am s.

Sw eat in g ov er a br ok en pr ogr am at 2 : 0 0 in t h e m or n in g on ly t o fin d y ou t y ped " = " w her e y ou should hav e t y ped " = = " is a v er y effect iv e lear ning ex per ience. Ther e ar e m an y pr ogr am m in g ex am ples u sed t h r ou gh ou t t h is book . Som e ex am ples don 't w or k as ex pect ed an d ar e posed as qu est ion s f or t h e r eader t o solv e. You ar e encour aged t o ent er each int o y our com put er , r un t he pr ogr am , and debug it . These ex er cises w ill in t r odu ce y ou t o com m on er r or s in sh or t pr ogr am s so t h at y ou w ill k n ow h ow t o sp ot an d cor r ect t h em in lar ger pr ogr am s of y ou r ow n . You w ill fin d an sw er s t o q u est ion s at t h e en d of each ch ap t er . Also, at t h e en d of m an y ch ap t er s, y ou w ill find a sect ion called " Pr ogr am m ing Ex er cises. " These sect ions cont ain

(13)

ex er cises t hat m ight be used in a pr ogr am m in g class t o t est y ou r k n ow ledge of C pr ogr am m ing.

N ot e s on t h e Th ir d Ed it ion

Th e C lan gu age h as ev olv ed sin ce t h e f ir st edit ion of Pr act ical C Pr ogr am m ing w a s pu blish ed. Back t h en , ANSI com piler s w er e r ar e an d com piler s t h at accept ed t h e K& R sy n t ax w er e com m on . Now t h e r ev er se is t r u e.

Th e t h ir d edit ion r eflect s t h e in du st r y sh ift t o ANSI com piler s. All pr ogr am s an d ex am ples h av e been u pdat ed t o con f or m t o t h e ANSI st an dar d. I n f act , t h e older K&R sy nt ax is discussed only in Chapt er 1 9 .

Ot h er ch an ges/ addit ion s t o t h e book in clu de:

• Addit ional inst r uct ions for m or e com piler s including a gener ic UNI X com piler , t he Fr ee Soft w ar e Foundat ions gcc com piler s, Bor land C+ + , Turb o C+ + , an d Micr osoft Visual C+ + .

• A com plet ely r ew r it t en Chapt er 2 2 . This chapt er now uses a st at ist ics pr ogr am t h at sh ou ld be m or e r elev an t t o a lar ger n u m ber of r eader s.

Finally, I am a pr act ical per son. I t end t o believ e t hat if y ou k now w hat I m ean and I k now w hat I m ean, t hen t he language has ser v ed it s pur pose. Thr oughout t his book , I u se t h e w or d " h e" t o den ot e a pr ogr am m er . A f ew people in t h e " Polit ically Cor r ect " cr ow d h ave labeled t h is pr act ice as sex ist . Th ey also h av e labeled som e passages in t h e book as bein g v iolen t or r acist .

Please n ot e t h at w h en I u se " h e, " I r efer t o a pr ogr am m er , w it h n o r egar d t o gen der . Secon dly , w h en I su ggest t h at som e bad pr ogr am m er s sh ou ld be sh o t , I d o n o t speak lit er ally .

My st y le h as alw ay s been t o com m u n icat e t h in gs clear ly , con cisely , an d w it h a bit of h u m or . I r egr et an y offen se t h at t h is m igh t cau se an y on e.

Fon t Con v e n t ion s

The follow ing conv ent ions ar e used in t his book :

I t alic

(14)

13

Bold

is u sed f or C k ey w or ds.

Const ant Widt h

is used in t ex t for pr ogr am s and t he elem ent s of a pr og r am and inex am ples t o show t he cont ent s of files or t he out put fr om com m ands. A r efer ence in t ex t t o a w or d or it em u sed in an ex am p le or cod e f r ag m en t is also sh ow n in con st an t-w id t h f on t .

Constant Bold

is u sed in ex am ples t o sh ow com m an ds or ot h er t ex t th at sh ou ld b e t y p ed lit er ally by t he user . ( For ex am ple, rm foo inst r uct s y ou t o t y pe " r m foo" ex act ly as it appear s in t he t ex t or ex am ple. )

Constant Italic

is u sed in ex am ples t o sh ow v ar iables for w h ich a con t ex t -specific

subst it ut ion should be m ade. ( The v ar iable filename, for ex am ple, w ou ld be r eplaced by som e act ual filenam e. )

" "

ar e u sed t o iden t ify sy st em m essages or code fr agm en t s in ex plan at or y t ex t .

%

is t h e UNI X sh ell pr om pt .

[ ]

su r r ou n d opt ion al v alu es in a descr ipt ion of pr ogr am sy n t ax . ( Th e br ack et s t hem selv es should nev er be t y ped. )

. . .

st ands for t ex t ( usually com put er out put ) t hat 's been om it t ed for clar it y or t o sav e space.

Th e n ot at ion CTRL-X o r ^X in d icat es u se of con t r ol char act er s. The not at ion inst r uct s y ou t o hold dow n t he " cont r ol" k ey w hile t y ping t he char act er " x " . We denot e ot her k ey s sim ilar ly ( e.g., RETURN in dicat es a car r iage r et u r n ) .

All ex am ples of com m an d lin es ar e follow ed by a RETURN u n less ot h er w ise in dicat ed.

(15)

Ob t a in in g Sou r ce Cod e

Th e ex er cises in t h is book ar e av ailable elect r on ically by FTP an d FTPMAI L. Use FTP if y ou ar e dir ect ly on t h e I n t er n et . Use FTPMAI L if y ou ar e n ot on t h e I n t er n et bu t can send and r eceiv e elect r onic m ail t o I nt er net sit es. ( This includes Com puSer v e users.)

FTP

I f y ou h av e an I n t er n et con n ect ion ( per m an en t or dialu p) , t h e easiest w ay t o u se FTP is v ia y our w eb br ow ser or fav or it e FTP client . To get t he ex am ples, sim ply point y ou r br ow ser t o:

ft p: / / ft p. or eilly . com / published/ or eilly / nut shell/ pr act ical_c3/ ex am ples. t ar . gz

I f y ou d on ' t h av e a w eb b r ow ser , y ou can u se t h e com m an d-line FTP client included w it h Window s NT ( or Window s 9 5 ) . I f y ou ar e on a PC, y ou can get ex am ples. zip inst ead o f ex am ples. t ar . gz.

% ftp ftp.oreilly.com

Connected to ftp.oreilly.com.

220 ftp.oreilly.com FTP server (Version 6.34 Thu Oct 22 14:32:01 EDT 1992) ready.

Name (ftp.oreilly.com:username ): anonymous

331 Guest login ok, send e-mail address as password.

Password: username@hostname Use your username and host here

230 Guest login ok, access restrictions apply. ftp> cd /published/oreilly/nutshell/practical_c3 250 CWD command successful.

ftp> binary

200 Type set to I.

ftp> get examples.tar.gz 200 PORT command successful.

150 Opening BINARY mode data connection for examples.tar.gz (xxxx bytes). 226 Transfer complete. local: exercises remote: exercises

xxxx bytes received in xxx seconds (xxx Kbytes/s) ftp> quit

(16)

15

FTPM AI L

FTP MAI L is a m ail ser v er av ailable t o an y on e w h o can sen d elect r on ic m ail t o, an d r eceiv e elect r onic m ail fr om , I nt er net sit es. Any com pany or ser v ice pr ov ider t hat allow s em ail connect ions t o t he I nt er net can access FTPMAI L.

You send m ail t o ft pm ail@online. oreilly.com . I n t h e m essage body , giv e t h e FTP com m an ds y ou w an t t o r u n . Th e ser v er w ill r u n an on y m ou s FTP f or y ou , an d m ail t h e files back t o y ou . To get a com plet e h elp file, sen d a m essage w it h n o su bj ect an d t h e sin gle w or d " h elp" in t h e body . Th e follo w in g is an ex am ple m ail m essage t hat get s t he ex am ples. This com m and sends y ou a list ing of t he files in t he select ed dir ect or y and t he r equest ed ex am ple files. The list ing is useful if y ou ar e int er est ed in a lat er v er sion of t h e ex am ples. I f y ou ar e on a PC, y ou can get ex am ples. zip inst ead of ex am ples. t ar . gz.

Subject:

reply -to username@hostname (Message Body) Where you want files mailed

open

cd /published/oreilly/nutshell/practical_c3 dir

mode binary uuencode

get examples.tar.gz quit

.

A sign at u r e at t h e en d of t h e m essage is accept able as lon g as it appear s af t er " quit ."

Com m e n t s a n d Qu e st ion s

We h av e t est ed an d v er ified all of t h e in for m at ion in t h is book t o t h e best of ou r abilit y , bu t y ou m ay f in d t h at f eat u r es h av e ch an ged ( or ev en t h at w e h av e m ad e m ist ak es! ) . Please let u s k n ow abou t an y er r or s y ou f in d, as w ell as y ou r

suggest ions for fut ur e edit ions, by w r it ing t o:

O'Reilly & Associat es, I nc.

1 0 0 5 Gr av en st ein High w ay Nor t h Sebast opol, CA 9 5 4 7 2

1 -8 0 0 -998 -9 9 3 8 ( in US or Can ada) 1 -7 0 7 -8 29 -0515 ( int er nat ional/ local) 1 -7 0 7 -829 -0104 ( FAX)

(17)

You can also sen d u s m essages elect r on ically . To be pu t on t h e m ailin g list or r equ est a cat alog, sen d em ail t o:

info@oreilly.com ( v ia t h e I n t er n et )

To ask t echnic al qu est ion s or com m en t on t h e book , sen d em ail t o:

book quest ions@or eilly .com ( v ia t he I nt er net )

We hav e a w eb sit e for t he book , w her e w e' ll list ex am ples, er r at a, and any plans for fut ur e edit ions. You ca n access t h is page at :

ht t p: / / w w w . or eilly . com / cat alog/ pcp3/

For m or e in for m at ion abou t t h is book an d ot h er s, see t h e O' Reilly w eb sit e:

(18)

17

Ack n ow le d g m e n t s

I w ish t o t h an k m y f at h er f or h is h elp in edit in g an d Ar t h u r Mar qu ez f or h is aid in for m at t ing t his book .

I am gr at efu l t o all t h e gan g at t h e Wr it er s' Hav en an d Book st or e, Pear l, Alex , an d Cly de, for t heir cont inued s uppor t . Thank s t o Peg Kov ar for help in edit ing. Special t h an k s t o Dale Dou gh er t y for r ippin g apar t m y book an d for cin g m e t o pu t it t oget her r ight . My t hank s also go t o t he pr oduct ion gr oup of O'Reilly &

Associat es—especially Rosanne Wagger and Mik e Sier r a —f or pu t t in g t h e f in ish in g t ouches on t his book . Finally , Jean Gr aham deser v es a special cr edit for put t ing up w it h m y w r it in g all t h ese y ear s.

(19)

Ack n ow le d g m e n t s t o t h e Th ir d Ed it ion

(20)

19

Pa r t I : Ba sics

Th is par t of t h e book t each es y ou t h e basic con st r u ct s of t h e C lan gu age. Wh en y ou ' r e fin ish ed, y ou ' ll be able t o w r it e w ell -design ed an d w ell- t h ou gh t -o u t C pr ogr am s. St y le is em ph asized ear ly so t h at y ou can im m ediat ely st ar t w r it in g pr ogr am s using a good pr ogr am m ing st y le. Alt hough y ou' ll be li m it ed t o sm all pr ogr am s t hr oughout t his par t , t hey 'll be w ell-w r it t en on es.

Chapt er 1 giv es a br ief descr ipt ion of t h e C lan gu age an d it s u se. Th is ch apt er in clu des som e back gr ou n d on t h e h ist or y of t h e lan g u ag e.

Chapt er 2 ex plain s t h e basic pr ogr am m in g pr ocess an d giv es y ou en ou gh infor m at ion t o w r it e a v er y sim ple pr ogr am .

Chapt er 3 discusses pr ogr am m ing st y le. Com m ent ing a pr ogr am is cov er ed, as w ell as w r it in g clear an d sim ple code.

Chapt er 4 in t r odu ces y ou t o sim ple C st at em en t s. Basic v ar iables an d t h e

assign m en t st at em en t ar e cov er ed in det ail, alon g w it h ar it h m et ic oper at or s + , - , * , / , and % .

Chapt er 5 cov er s ar r ay s and m or e com plex v ar iables. Shor t hand oper at or s such as + + an d % = ar e also descr ibed.

Chapt er 6 ex plains sim ple decision st at em ent s including if , e lse , a n d for. A discussion of = = v er sus = is pr ese n t ed .

Chapt er 7 t ak es y ou t h r ou gh all t h e n ecessar y st eps t o cr eat e a sim ple pr ogr am fr om specificat ion t hr ough r elease. St r uct ur ed pr ogr am m ing, fast pr ot ot y ping, and debu ggin g ar e also discu ssed.

(21)

Cha pt e r 1 . W ha t I s C?

Pr ofanit y is t he one language t hat all pr ogr am m er s under st and.

—Anon.

The abilit y t o or ganize and pr ocess infor m at ion is t he k ey t o success in

t he m odern age. Com put ers are designed t o handle and process large

am ount s of infor m at ion quickly and efficient ly, but t hey can't do

any t hing unt il som eone t ells t hem w hat t o do.

That 's where C com es in. C is a program m ing language t hat allows a

soft w are engineer t o efficient ly com m unicat e w it h a com put er.

C is a highly flexible and adapt able language. Since it s creat ion in

1970, it 's been used for a wide variet y of program s including firm ware

for m icro - cont rollers, operat ing syst em s, applicat ions, and graphics

program m ing.

C is one of t he m ost m ost w idely used languages in t he w orld and is

fairly st able. An im proved C language called C+ + has been invent ed,

but it is st ill in developm ent , and it s definit ion is st ill being worked on.

C+ + , or iginally k now n as C w it h Classes, adds a num ber of new

feat ur es t o t he C language, t he m ost im por t ant of w hich is t he class.

Classes facilit at e code r euse t hr ough obj ect -orient ed design ( OOD) .

Which is bet t er , C or C+ + ? The answ er depends on w ho y ou t alk t o.

C+ + does gr eat t hings for y ou behind y our back , such as

aut om at ically calling const r uct ors and dest ruct ors for variables. This

pr ocessing m ak es som e t y pes of pr ogr am m ing easy , but it m ak es

st at ic check ing of pr ogr am s difficult , and y ou need t o be able t o t ell

exact ly w hat your pr ogr am is doing if you ar e w or king on em bedded

cont r ol applicat ions. So som e people consider C+ + t he bet t er

language because it does t hings aut om at ically and C doesn't . Ot her

people consider C bet t er for pr ecisely t he sam e r eason.

(22)

21

1 . 1 H ow Pr og r a m m in g W or k s

Com m unicat ing w it h com put ers is not easy. They require inst ruct ions

t hat ar e exact and det ailed. I t w ould be nice if w e could w r it e

pr ogr am s in English. Then w e could t ell t he com put er , " Add up all m y

check s and deposit s, t hen t ell m e t he t ot al," and t he m achine w ould

balance our checkbook.

But English is a lousy language w hen it com es t o w rit ing exact

inst r uct ions. The language is full of am biguit y and im pr ecision. Gr ace

Hopper , t he gr and old lady of com put ing, once com m ent ed on t he

inst r uct ions she found on a bot t le of sham poo:

Wash Rinse Repeat

She t r ied t o follow t he dir ect ions, but she r an out of sham poo.

( Wash-Rinse -Repeat . Wash- Rinse- Repeat . Wash-Rinse- Repeat...)

Of cour se, w e can t r y t o w r it e in pr ecise English. We'd hav e t o be

car eful and m ak e sur e t o spell ev er y t hing out and be sur e t o include

inst r uct ions for ev er y cont ingency . But if w e w or k ed r eally har d, w e

could w r it e pr ecise English inst r uct ions.

I t t urns out t hat t here is a group of people who spend t heir t im e t rying

t o w r it e pr ecise English. They'r e called t he gover nm ent , and t he

docum ent s t hey writ e are called governm ent regulat ions.

Unfort unat ely, in t heir effort t o m ake t he regulat ions precise, t he

gov er nm ent has m ade t hem alm ost unr eadable. I f y ou'v e ev er r ead

t he inst ruct ion book t hat com es w it h your t ax form s, you know w hat

pr ecise English can be lik e.

St ill, ev en w it h all t he ex t r a v er biage t hat the gover nm ent put s in,

problem s can occur. A few years ago California passed a law requiring

all m ot orcycle riders t o wear a helm et . Short ly aft er t his law went int o

effect , a cop st opped a guy for not w ear ing one. The m an suggest ed

t he policem an t ak e a closer look at t he law .

The law had t w o r equir em ent s: 1) t hat m ot or cycle r ider s have an

appr ov ed cr ash helm et and 2) t hat it be fir m ly st r apped on. The cop

couldn't give t he m ot or cyclist a t icket because he did have a helm et

firm ly st rapped on—t o his k nee.

(23)

So English, wit h all it s problem s, is out . Now, how do we com m unicat e

wit h a com put er?

The first com put ers cost m illions of dollars, w hile at t he sam e t im e a

good pr ogr am m er cost about $15,000 a y ear . Pr ogr am m er s w er e

forced t o program in a language in whic h all t he inst r uct ions w er e

r educed t o a ser ies of num ber s, called

m achine language

. This

language could be direct ly input int o t he com put er. A t ypical

m achine -language program looks like:

1010 1111

0011 0111

0111 0110

.. and so on for several hundred inst ructions

While m achines " t hink" in num bers, people don't . To program t hese

ancient m achines, soft w ar e engineer s w ould w r it e t heir pr ogr am s

using a sim ple language in w hich each w ord in t he language st ood for

a single inst ruct ion. This language w as called

assem bly language

because t he pr ogr am m er s had t o hand t r anslat e, or assem ble, each

line int o m achine code.

A t ypical program m ight look like:

Program

Translation

MOV A,47

1

010 1111

ADD A,B

0011 0111

HALT

0111 0110

.. and so on for several hundred instructions

This process is illust rat ed by Figur e 1 - 1 .

(24)

23

Tr anslat ion w as a difficult , t edious, and exact ing t ask. One soft w ar e

engineer decided t hat t his w as a per fect j ob for a com put er , so he

w r ot e a pr ogr am called an assem bler t hat w ould do t he j ob

aut om at ically .

He show ed his new cr eat ion t o his boss and w as im m ediat ely chew ed

out : " How dar e y ou ev en t hink of using such an ex pensiv e m achine for

a m er e ` cler ical' t ask." Given t he cost of an hour of com put er t im e

v er sus t he cost of an hour of pr ogr am m er t im e, t his at t it ude w as not

unreasonable.

For t unat ely, as t im e passed t he cost of pr ogr am m er s w ent up and t he

cost of com put er s w ent dow n. So let t ing t he pr ogr am m er s w r it e

pr ogr am s in assem bly language and t hen using a pr ogr am called an

assem bler t o t ranslat e t hem int o m achine language becam e very cost

effect iv e.

Assem bly language or ganized pr ogr am s in a w ay t hat w as easy for

t he pr ogr am m er s t o under st and. How ever , t he pr ogr am w as m or e

difficult for t he m achine t o use. The pr ogr am had t o be t r anslat ed

befor e t he m achine could execut e it . This m et ho d w as t he st ar t of a

t rend. Program m ing languages becam e m ore and m ore convenient

for t he pr ogr am m er t o use, and st ar t ed r equir ing m or e and m or e

com put er t im e for t ranslat ion int o som et hing useful.

Ov er t he y ear s, a ser ies of

higher -lev el

languages hav e been devised.

These languages at t em pt t o let t he pr ogr am m er w r it e in a m edium

t hat is easy for him t o underst and, and t hat is also precise and sim ple

enough for t he com put er t o under st and.

Ear ly high- level languages w er e designed t o handle specific t ypes of

applicat ions. FORTRAN w as designed for num ber cr unching, COBOL

w as for w r it ing business r epor t s, and PASCAL w as for st udent use.

( Many of t hese languages hav e far out gr ow n t heir init ial uses.

Nicklaus Wirt h has been rum ored t o have said, " I f I had known t h at

PASCAL w as going t o be so successful, I w ould hav e been m or e

careful in it s design." )

1 . 2 Br ie f H ist or y of C

I n 1970 a pr ogr am m er , Dennis Rit chie, cr eat ed a new language called

C. ( The nam e cam e about because it superceded t he old

program m ing language he w as using: B.) C w as designed w it h one

goal in m ind: w rit ing operat ing syst em s. The language w as ext rem ely

(25)

sim ple and flex ible, and soon w as used for m any differ ent t y pes of

pr ogr am s. I t quickly becam e one of t he m ost popular pr ogr am m ing

languages in t he w or ld .

C's popular it y w as due t o t w o m aj or fact or s. The fir st w as t hat t he

language didn't get in t he w ay of t he pr ogr am m er . He could do j ust

about any t hing by using t he pr oper C const r uct . ( As w e w ill see, t his

flexibilit y is also a draw back, as it allows t he program t o do t hings t hat

t he program m er never int ended.)

The second r eason t hat C is popular is t hat a por t able C com piler w as

w idely available. Consequent ly, people could at t ach a C com piler for

t heir m achine easily and w it h lit t le ex pense.

I n 1980, Bj ar ne St r oust r up st ar t ed w or king on a new language, called

" C w it h Classes." This language im pr ov ed on C by adding a num ber of

new feat ures. This new language was im proved and augm ent ed, and

finally becam e C+ + .

One of t he new est languages, Jav a, is based on C+ + . Jav a w as

designed t o be " C+ + w it h t he bugs fixed." At t he t im e of t his w r it ing,

Jav a has lim it ed use despit e being heav ily m ar k et ed by Sun

Micr osyst em s and ot her s.

1 .3 H ow C W or k s

C is designed as a br idge bet w een t he pr ogr am m er and t he r aw

com pu t er. The idea is t o let t he program m er organize a program in a

w ay t hat he can easily under st and. The com piler t hen t r anslat es t he

language int o som et hing t hat t he m achine can use.

Com put er pr ogr am s consist of t w o m ain par t s: dat a and inst r uct ions.

Th e com put er im poses lit t le or no organizat ion on t hese t w o part s.

Aft er all, com put er s ar e designed t o be as gener al as possible. The

pr ogr am m er should im pose his or ganizat ion on t he com put er , not t he

ot her w ay around.

The dat a in a com put er is st ored as a serie s of by t es. C or ganizes

t hose by t es int o useful dat a. Dat a declar at ions ar e used by t he

program m er t o describe t he inform at ion he is w orking w it h. For

ex am ple:

(26)

25

t ells C t hat w e w ant t o use a sect ion of t he com put er's m em or y t o

st ore an int eger nam ed

total

. We let t he com piler decide w hat

par t icular byt es of m em or y t o use; t hat decision is a m inor

book k eeping det ail t hat w e don't w ant t o w or r y about .

Our variable

total

is a sim ple variable. I t can hold only one int eg er

and descr ibe only one t ot al. A ser ies of int eger s can be or ganized int o

an ar r ay as follow s:

int balance[100]; /* Balance (in cents) for all 100 accounts

*/

Again, C w ill handle t he det ails of im posing t hat or ganizat ion on t he

com put er 's m em or y. Finally , t her e ar e m or e com plex dat a t y pes. For

exam ple, a rect angle m ight have a widt h, a height , a color, and a fill

pat t er n. C let s us or ganize t hese four it em s int o one gr oup called a

st r uct ur e.

struct rectangle {

int width; /* Width of rectangle in pixels */

int height; /* Height of rectangle in pixels */

color_type color; /* Color of the rectangle */

fill_type fill; /* Fill pattern */

};

The point is t hat st ruct ures allow t he program m er t o arrange t he dat a

t o suit his needs n o m at t er how sim ple or com plex t hat dat a is.

Tr anslat ion of t his dat a descr ipt ion int o som et hing t he com put er can

use is t he j ob of t he com piler, not t he program m er.

But dat a is only one part of a program . We also need inst ruct ions. As

far as t he com put er is concerned, it knows not hing about t he layout of

t he inst ruct ions. I t know s w hat it 's doing for t he current inst ruct ion

and w her e t o get t he nex t one, but not hing m or e.

C is a high- level language. I t let s us w r it e a high- level st at em ent like:

area = (bas e * height) / 2.0; /* Compute area of triangle */

The com piler w ill t r anslat e t his st at m ent int o a ser ies of cr ypt ic

low - level m achine inst r uct ions. This sor t of st at em ent is called an

assignm ent st at em ent

. I t is used t o com put e and st ore t he value of an

arit hm et ic expression.

(27)

We can also use

cont r ol st at em ent s

t o cont rol t he order of processing.

St at em ent s like t he if

and sw it ch st at em ent s enable t he com put er t o

m ak e sim ple decisions. St at em ent s can be r epeat ed ov er and ov er

again by using looping st at em ent s such as

w hile

and

for .

Gr oups of st at em ent s can be w r apped t o for m funct ions. Thus, w e

only hav e t o w r it e a gener al-pur pose funct ion t o dr aw a r ect angle

once, and t hen w e can r euse it w henev er w e w ant t o dr aw a new

rect angle.

C pr ovides t he pr ogr am w it h a r ich set of

st andard funct ions

t hat

per for m com m on funct ions such as sear ching, sor t ing, input , and

out put .

A set of relat ed funct ions can be grouped t oget her in a single source

file. Many source files can be com piled and linked t oget her t o form a

pr ogr am .

One of t he m aj or goals of t he C language is t o or ganize inst r uct ions

int o r eusable com ponent s. Aft er all, y ou can w r it e pr ogr am s m uch

fast er if you can " bor r ow " m ost of your code fr om som ew her e else.

Gr oups of r eusable funct ions can be com bined int o a library. I n t his

m anner, when you need, for exam ple, a sort rout ine, you can grab t he

st andard funct ion

qsort

fr om t he libr ar y and link it int o y our pr ogr am .

The dat a declarat ions, st ruct ures and cont rol st at em ent s, and ot her C

language elem ent s, are not for t he com put er 's benefit . The com put er

can't t ell t he differ ence bet w een a m illion r andom by t es and a r eal

pr ogr am . All t he C language elem ent s ar e designed t o allow t he

pr ogr am m er t o ex pr ess and or ganize his ideas clear ly in a m anner

t ailored t o him , no t t o t he com put er.

Or ganizat ion is t he k ey t o w r it ing good pr ogr am s. For ex am ple, in t his

book you know t hat t he Table of Cont ent s is in t he front and t he I ndex

is in t he back. We use t his st ruct ure because books are organized t hat

w ay . Or ganizat ion m ak es t his book easier t o use.

(28)

27

1 . 4 H ow t o Le a r n C

Th er e is on ly on e w ay t o lear n h ow t o p r og r am an d t h at is t o w r it e p r og r am s. You ' ll lear n a lot m or e by w r it in g an d debu ggin g pr ogr am s t h an y ou ev er w ill by r eadin g t h is book . Th is book con t ain s m an y pr ogr am m in g ex er cises. You sh ou ld t r y t o do as m any of t hem as possib le. When y ou do t he ex er cises, k eep good pr ogr am m ing st y le in m ind. Alw ay s com m ent y our pr ogr am s, ev en if y ou'r e only doing t he ex er cises for y ou r self. Com m en t in g h elps y ou or gan ize y ou r t h ou gh t s an d k eeps y ou in pr act ice w h en y ou go in t o t h e r eal w or ld.

Don ' t let y ou r self be sedu ced by t h e idea t h at " I ' m on ly w r it in g t h ese pr ogr am s for m y self, so I don't need t o com m ent t hem . " Fir st of all, code t hat look s obv ious t o a pr ogr am m er as h e w r it es it is of t en con f u sin g an d cr y pt ic w h en h e r ev isit s it a w eek lat er . Wr it in g com m en t s also h elps y ou t o get or gan ized bef or e y ou w r it e t h e act u al code. ( I f y ou can w r it e out an idea in English, y ou'r e halfw ay t o w r it ing it in C. )

Fin ally , pr ogr am s t en d t o be ar ou n d f ar lon ger t h an ex pect ed. I on ce w r ot e a pr ogr am t hat w as design ed t o w or k on ly on t h e com pu t er at Calt ech . Th e pr ogr am w as h igh ly sy st em-depen den t . Becau se I w as t h e on ly on e w h o w ou ld ev er u se it , t h e pr ogr am w ou ld pr in t t h e f ollow in g m essage if y ou got t h e com m an d lin e w r on g:

?LSTUIT User is a twit

A few y ear s lat er , I w as a st udent at Sy r acuse Univ er sit y , and t he Secr et ar y at t he School of Com put er Science needed a pr ogr am t hat w as sim ilar t o m y Calt ech list ing pr ogr am . So I adapt ed m y pr ogr am for her use. Unfor t unat ely , I for got about t he er r or m essage.

I magin e h ow h or r if ied I w as w h en I cam e in t o t h e Com pu t er Scien ce of f ice an d w as accost ed by t he Chief Secr et ar y . This lady had so m uch pow er t hat she could m ak e t h e Dean cr in g e. Sh e look ed at m e an d said , " User is a t w it , h u h ! " Lu ck ily sh e h ad a sen se o f h um or , or I w ouldn't be her e t oday .

Spr ink led t hr oughout t his book ar e m any br ok en pr ogr am s. Spend t he t im e t o figu r e ou t w h y t h ey don ' t w or k . Oft en , t h e pr oblem is v er y su bt le, su ch as a m isplaced sem icolon or t h e u se of = in st ead of ==. Th ese pr ogr am s let y ou lear n h ow t o spot m ist ak es in a sm all pr ogr am . Th en , w h en y ou m ak e sim ilar m ist ak es in a big pr ogr am , and y ou w ill m ak e m ist ak es, y ou w ill be t r ained t o spot t hem .

(29)

Cha pt e r 2 . Ba sics of Pr ogr a m W r it ing

The fir st and m ost im por t ant t hing of all, at least for w r it er s t oday, is

t o st rip language clean, t o lay it bare dow n t o t he bone.

—Ernest Hem ingw ay

Pr ogr am s st ar t as a set of inst r uct ions w r it t en by a hum an being.

Befor e t hey can be used by t he com put er , t hey m ust under go sev er al

t ransform at ions. I n t his chapt er, w e'll learn how t o ent er a program ,

t ransform it int o som et hing t he m achine can use, and run it . Det ailed

st eps ar e pr ovided for t he m ost popular UNI X and DOS/ Window s

com pilers.

2 .1 Pr og r a m s f r om Con ce p t ion t o Ex e cu t ion

C program s are w rit t en in a high - level language using let t ers,

num ber s, and t he ot her sy m bols y ou find on a com put er k ey boar d.

Com put er s act ually ex ecut e a v er y low-level language called

m achine

code

( a series of num bers) . So, before a program level can be used, it

m ust under go sever al t r ansfor m at ions.

Pr ogr am s st ar t out as an idea in a pr ogr am m er 's head. He uses a t ex t

edit or t o writ e his t hought s int o a file called a

source file

, cont aining

sour ce code.

This file is t r ansfor m ed by t he

com piler

int o an

obj ect file

.

Next , a progra m called t he

link er

t ak es t he obj ect file, com bines it

w it h predefined rout ines from a

st andar d libr ar y ,

and pr oduces an

ex ecut able pr ogr am

( a set of m achine - language inst r uct ions)

.

I n t he

follow ing sect ions, w e'll see how t hese v ar ious for m s of t he pr ogr am

w or k t oget her t o pr oduce t he final pr ogr am .

Figure 2 -1 show s t he st eps t hat m ust be t ak en t o t r ansfor m a

(30)

29

Figur e 2 - 1 . Tr a nsfor m a t ion of a high- le ve l la ngua ge

in t o a pr ogr a m

2 .1 .1 W r a ppe r s

For t unat ely y ou don't hav e t o r un t he com piler , assem bler , and link er

ind ividually. Most C com pilers use " w rapper" program s t hat

det er m ine w hich t ools need t o be r un and t hen r un t hem .

Som e program m ing syst em s go even furt her and provide t he

developer w it h an I nt egrat ed Developm ent Environm ent ( I DE) . The

I DE cont ains an edit or, com piler, linker, proj ect m anager, debugger,

and m ore in one convenient package. Bot h Borland and Microsoft

provide I DEs wit h t heir com pilers.

2 . 2 Cr e a t in g a Re a l Pr og r a m

Befor e w e can act ually st ar t cr eat ing our ow n pr ogr am s, w e need t o

k now how t o use t he basic pr ogr am m ing t ools. I n t his sect ion, w e w ill

t ak e y ou st ep by st ep t hr ough t he pr ocess of ent er ing, com piling, and

r unning a sim ple pr ogr am .

(31)

We w ill descr ibe how t o use t w o differ ent t y pes of com piler s. The fir st

t y pe is t he st andalone or com m and- line com piler . This t y pe of

com piler is operat ed in a bat ch m ode from t he com m and line. I n ot her

w or ds, y ou t y pe in a com m and, and t he com piler t ur ns y our sour ce

code int o an execut able pr ogr am .

The ot her t ype of com piler is cont ained in an I DE. The I DE cont ains an

edit or , com piler , pr oj ect m anager , and debugger in one pack age.

Most UNI X sy st em s use com m and- line com pilers. There are a few I DE

com pilers available for UNI X, but t hey are rare. On t he ot her hand,

alm ost ev er y com piler for MS- DOS/ Window s cont ains an I DE. For t he

com m and- line die - har ds, t hese com piler s do cont ain a com m and -line

com piler as w ell.

2 .3 Cr e a t in g a Pr og r a m U sin g a Com m a n d - Lin e

Com pile r

I n t h is sect ion , w e' ll go t h r ou gh t h e st ep-b y -st ep p r ocess n eed ed t o cr eat e a pr ogr am u sin g a com m an d -line com piler . I nst r uct ions ar e pr ov ided for a gener ic UNI X com piler ( cc) , t he Fr ee Soft w ar e Foundat ion's gcc com piler , Tur bo C+ + , Bor land C+ + , and Micr osoft Visual C+ + .[ 1]

[ 1]

Tur bo C+ + , Bor land C+ + , and Micr osoft Visual C+ + ar e all C+ + com piler s t hat can also com pile C code.

How ev er , if y ou ar e u sin g a Bor lan d or Micr osoft com piler , y ou m igh t w an t t o sk ip ah ead t o t h e sect ion on u sin g t h e I DE.

2 .3 .1 St e p 1 . Cr e a t e a Pla ce for You r Pr ogr a m

You can m or e easily m anage t hings if y ou cr eat e a separ at e dir ect or y for each pr ogr am t h at y ou ' r e w or k in g on . I n t h is case, w e' ll cr eat e a dir ect or y called h ello t o h old ou r h ello pr ogr am .

On UNI X t y pe:

% mkdir hello % cd hello

On MS-D OS t y p e:

(32)

31

2 .3 .2 St e p 2 . Cr e a t e t h e Pr ogr a m

A p r og r am st ar t s ou t as a t ex t f ile. Ex am ple 2 -1 sh ow s ou r pr ogr am in sou r ce f or m .

Ex a m p le 2- 1 .

hello/ hello.c

[File: hello/hello.c] #include <stdio.h> int main()

{

printf("Hello World\n"); return (0);

}

Use y ou r fav or it e t ex t edit or t o en t er t h e pr ogr am . You r file sh ou ld be n am ed

h ello. c.

MS- DOS/ Window s user s should

n ot

use a w or d

pr ocessor such as MS- Wor d or Wor dPer fect t o w r it e

t heir program s. Word processors add form at t ing

codes t o files, w hich confuse t he com piler . You m ust

use a t ext ed it or such as t he MS- DOS " EDI T" pr ogr am

t hat is capable of edit ing ASCI I files.

2 .3 .3 St e p 3 . Ru n t h e Com pile r

The com piler t ak es t he sour ce file y ou' v e j ust m ade and conv er t s it int o an ex ecut able pr ogr am . Each com piler has a differ ent com m and line. The com m an d s for t he m ost popular com piler s ar e list ed below .

2 .3 .3 .1 UN I X cc com pile r ( ge n e r ic UN I X)

Most UNI X -based com piler s follow t he sam e gener ic st andar d. The C com piler is n am ed cc, an d t o com pile ou r h ello pr ogr am w e n eed t h e f ollow in g com m an d:

% cc -g -ohello hello.c

The -g opt ion en ables debu ggin g. ( Th e com piler adds ex t r a in f or m at ion t o t h e pr ogr am t o m ak e t he pr ogr am easier t o debug. ) The sw it ch -ohello t ells t h e com piler t h at t h e pr ogr am is t o be called hello, and t he final hello.c is t h e n am e o f t h e sou r ce f ile. See y ou r com piler m an u al f or det ails on all t h e possible opt ion s.

(33)

Th er e ar e sev er al differ en t C com piler s for UNI X, so y ou r com m an d lin e m ay be slight ly differ ent .

2 .3 .3 .2 Fr e e Soft w a r e Founda t ion's gcc com pile r

Th e Fr ee Sof t w ar e Fou n dat ion , t h e GNU people, pu blish a n u m ber of h igh-qualit y pr ogr am s. ( See t he Glossar y ent r y for infor m at ion on how t o get t heir soft w ar e. ) Am ong t heir offer ings is a C com piler called gcc.

To com pile a pr ogr am u sin g t h e gcc com piler u se t h e follow in g com m an d lin e :

% gcc -g -Wall -ohello hello.c

The addit ional sw it ch -Wall t u r n s on t h e w ar n in g s.

The GNU com piler cont ains sev er al ex t ensions t o t he basic C language. I f y ou w ant t o t u r n t h ese f eat u r es off, u se t h e f ollow in g com m an d lin e:

% gcc -g -Wall -ansi -pedantic -ohello hello.c

The sw it ch -ansi t u r n s of f f eat u r es of GNU C t h at ar e in com pat ible w it h ANSI C. Th e

-pedantic sw it ch cau ses t h e com piler t o issu e a w ar n in g for an y n on-ANSI feat ur e it en cou n t er s.

2 .3 .3 .3 Bor la n d's Tu r bo C+ + u n de r M S- DOS

Bor land I nt er nat ion al m ak es a low -cost MS- DOS C+ + com piler called Tur bo C+ + . Th is com piler w ill com pile bot h C an d C+ + code. We w ill descr ibe on ly h ow t o com pile C code. Tur bo C+ + is ideal for lear ning. The com m and line for Tur bo C+ + is:

C:> tcc -ml -v -N -w -ehello hello.c

The -ml t ells Tu r bo C+ + t o u se t h e lar ge -m em or y m odel. ( Th e PC h as a lar ge n u m ber of differ en t m em or y m odels. On ly ex per t PC pr ogr am m er s n eed t o k n ow t h e differ en ce bet w een t h e v ar iou s m odels. For n ow , j u st u se t h e lar ge m odel u n t il y ou k now m or e. )

The -v sw it ch t ells Tur bo C+ + t o put debugging infor m at ion in t he pr ogr am . War n in gs ar e t u r n ed on by -w; st ack ch eck in g is t u r n ed on by -N. Finally -ehello

(34)

33

W in dow s Pr ogr a m m in g

You m ay w onder w hy w e descr ibe MS-DOS program m ing when

Window s is w idely used. We do so because program m ing in

Windows is m uch m ore com plex t han program m ing in

MS- DOS.

For ex am ple, t o print t he m essage " Hello World" in MS- DOS,

y ou m er ely pr int t he m essage.

I n Window s, y ou m ust cr eat e a w indow , cr eat e a funct ion t o

handle t he m essages fr om t hat w indow , select a font , select a

place t o put t he font , and out put t he m essage.

You m u st lear n t o w alk befor e y ou can r un. Ther efor e, w e lim it

y ou t o t he MS- DOS or Easy- Win ( Sim plified Windows)

pr ogr am s in t his book .

2 .3 .3 .4 Bor la n d C+ + u n de r M S- DOS a nd W indow s

I n addit ion t o Tu r bo C+ + , Bor lan d I n t er n at ion al also m ak es a fu ll-feat ur ed,

profe ssional com piler for MS-DOS/ Window s called Bor land C+ + . I t s com m and line is:

C:> bcc -ml -v -N -P -w -ehello hello.c

Th e com m an d-lin e opt ion s ar e t h e sam e f or bot h Tu r bo C+ + an d Bor lan d C+ + .

2 .3 .3 .5 M icr osoft Visua l C+ +

Micr osof t Visu al C+ + is an ot h er C+ + /C com p iler f or MS- DOS/ Window s. To com pile, u se t h e f ollow in g com m an d lin e:

C:> cl /AL /Zi /W1 hello.c

The /AL opt ion t ells t h e pr ogr am t o u se t h e lar ge m em or y m odel. Debu ggin g is t u r n ed on w it h t h e /Zi op t ion an d w ar n in g s w it h t h e /W1 opt ion .

2 .3 .4 St e p 4 . Ex e cu t e t h e Pr ogr a m

To r u n t h e pr ogr am ( on UNI X or MS-DOS/ Win dow s) t y pe:

(35)

% hello

an d t h e m essag e:

Hello World

w ill appear on t h e scr een .

2 . 4 Cr e a t in g a Pr og r a m U sin g a n I n t e g r a t e d

D e v e lopm e n t En v ir on m e n t

I n t egr at ed Dev elopm en t En v ir on m en t s ( I DEs) pr ov ide a on e -st op shop for

pr ogr am m ing. They t ak e a com piler , edit or , and debugger and w r ap t hem int o one neat pack age for t he pr ogr am .

2 .4 .1 St e p 1 . Cr e a t e a Pla ce for You r Pr ogr a m

You can m or e easily m anage t hings if y ou cr eat e a separ at e dir ect or y for each pro gr am t hat y ou'r e w or k ing on. I n t his case, w e'll cr eat e a dir ect or y called HELLO t o hold our hello pr ogr am .

On MS-D OS t y p e:

C:> MKDIR HELLO C:> CD HELLO

2 .4 .2 St e p 2 . Ent e r , Com pile , a nd Run Your Pr ogr a m

Usin g t h e I D E

Each I DE is a lit t le differ en t , so w e'v e in clu ded separ at e in st r u ct ion s f or each on e.

2 .4 .2 .1 Tur bo C+ +

1 . St ar t t h e Tu r bo C+ + I DE w it h t h e com m an d:

C:> TC

(36)

35

Figur e 2 - 2 . Cle a n de sk t op

3 . Select t h e Opt ions| Com piler | Code Gener at ion m en u it em t o pu ll u p t h e Code Gen er at ion dialog as seen in Figur e 2 -3 . Ch an ge t h e m em or y m odel t o Lar g e.

Figur e 2 - 3 . Code Ge ne r a t ion dia log

4 . Select t h e Opt ions| Com piler | Ent r y / Ex it m en u it em an d t u r n on " Test st ack ov er f low " as seen in Figur e 2 -4 .

(37)

Fig u r e 2 - 4 . Ent r y/ Ex it Code Ge ne r a t ion dia log

5 . Select t h e Opt ions| Com piler | Messages| Display m en u it em t o b r in g u p t h e Com piler Messages dialog as seen in Figur e 2 -5 . Select All t o display all t he w ar n in g m essages.

Figur e 2 - 5 . Com piler M essa ges dia log

(38)

37

Figur e 2 - 6 . Ope n Pr oj e ct File dia log

8 . Pr ess t h e INSERT k ey t o add a f ile t o t h e p r oj ect . Th e f ile w e w an t t o ad d is

HELLO.C as seen in Figure 2 -7 .

Figu r e 2 - 7 . Add t o Pr oj e ct List dia log

9 . Pr ess ESC t o g et ou t of t h e ad d -file cycle.

1 0 .Pr ess UP-ARROW t o go u p on e lin e. Th e lin e w it h HELLO. C sh ou ld n ow b e highlight ed as seen in Figur e 2 -8 .

(39)

Figu r e 2 - 8 . H e llo pr oj e ct

1 1 .Pr ess ENTER t o edit t his file. 1 2 .Ent er Ex am ple 2 -2 .

Ex a m ple 2- 2 .

hello/ hello.c

[File: hello/hello.c] #include <stdio.h> int main()

{

printf("Hello World\n"); return (0);

}

(40)

39

Figu r e 2 - 9 . Fin ish e d pr oj e ct

1 3 .Select t h e Run| Run m en u it em t o ex ecu t e t h e pr ogr am .

1 4 .Aft er t he pr ogr am r uns, cont r ol r et ur ns t o t he I DE. This con t r ol change m ean s t h at y ou can ' t see w h at y ou r pr ogr am ou t pu t . To see t h e r esu lt s of t h e pr ogr am y ou m u st sw it ch t o t h e u ser scr een by select in g t h e

Win dow | User m en u it em .

To r et ur n t o t he I DE, pr ess any k ey . Figur e 2 -1 0 sh ow s t h e ou t p u t of t h e program .

Figu r e 2 - 1 0 . Use r scr e e n

(41)

1 5 .Wh en y ou ar e f in ish ed, y ou can sav e y ou r pr ogr am by select in g t h e File| Sav e

m en u it em .

1 6 .To ex it t h e I DE, select t h e File| Quit m enu it em .

2 .4 .2 .2 Bor la nd C+ +

1 . Cr eat e a dir ect or y called \HELLO t o h old t h e f iles f or ou r Hello Wor ld pr ogr am . You can cr eat e a dir ect or y u sin g t h e Win dow s' File Man ager pr ogr am or b y t y pin g t h e f ollow in g com m an d at t h e MS- DOS pr om pt :

C:> mkdir \HELLO

2 . Fr om Window s, double -click on t h e " Bor lan d C+ + " icon t o st ar t t h e I DE. Select t h e Window | Close all m en u it em t o clean ou t an y old j u n k . Th e pr ogr am begin s ex ecu t ion an d display s a blan k w or k space as seen in Figure 2 -1 1 .

Figu r e 2 - 1 1 . Bor la n d C+ + in it ia l scr e e n

3 . Select t h e Pr oj ect | New Pr oj ect m enu it em t o cr eat e a pr oj ect for our

(42)

41

Figu r e 2 - 1 2 . N ew Ta rget dia log

4 . Click on t h e Adv anced bu t t on t o br in g u p t h e Adv an ced Opt ion s dialog. Clear t h e . r c an d . d ef it em s an d set t h e . c Node it em s as sh ow n in Figur e 2 -1 3 . 5 . Click on OK t o r et u r n t o t h e New Tar get dialog. Click on OK a gain t o r et u r n t o

t h e m ain w in d ow .

Figur e 2 - 1 3 . Adva nce d Opt ions dia log

(43)

6 . Pr ess ALT-F10 t o br ing up t he node subm enu show n in Figure 2 -1 4 .

Figur e 2 - 1 4 . Ta r ge t Opt ions subm e nu

7 . Select t h e Edit node at t r ibut es m en u it em t o br in g u p t h e dialog show n in Figure 2 -1 5 . I n t h e St y le Sheet blan k , select t h e it em Deb u g I n f o an d Diagnost ics. Click on OK t o r et u r n t o t h e m ain w in d ow .

(44)

43

8 . Go t o t h e Pr oj ect Opt ion s dialog by select in g t h e Opt ions| Pr oj ect Opt ions

m en u it em . Go dow n t o t h e Com piler it em an d click on t h e + t o ex pan d t h e op t ions.

Tu r n on t h e Test st ack ov er flow op t ion as seen in Figure 2 -1 6 . Click on OK t o sav e t hese opt ions.

Figur e 2 - 1 6 . Pr oj e ct Opt ion s dia log

9 . Click on OK t o r et u r n t o t h e m ain w in dow . Pr ess DOWN-ARROW t o select t h e

h ello[ . C] it em in t h e pr oj ect as seen in Figur e 2 -1 7 .

(45)

Figur e 2 - 1 7 . H e llo pr oj e ct

1 0 .Pr ess RETURN t o st ar t edit in g t h e f ile h ello. c. Ty pe in Ex am ple 2 -3 .

Ex a m ple 2- 3 .

hello/ hello.c

#include <stdio.h> int main()

{

printf("Hello World\n"); return (0);

}

(46)

45

Figu r e 2 - 1 8 . H e llo W or ld pr ogr a m

1 1 .Com pile an d r u n t h e pr ogr am by select in g t h e Debug| Run m en u it em . Th e pr ogr am w ill r un and dis play " Hello Wor ld" in a w in dow as seen in Figu r e 2 -1 9 .

Figu r e 2 - 1 9 . H e llo W or ld pr ogr a m a ft e r

e x e cut ion

(47)

2 .4 .2 .3 M icr osoft Visua l C+ +

1 . Cr eat e a dir ect or y called \HELLO t o h old t h e f iles f or ou r Hello Wor ld pr ogr am . You can cr eat e a dir ect or y u sin g t h e Win dow s' File Manager pr ogr am or by t y pin g t h e f ollow in g com m an d at t h e MS- DOS p r om pt :

C:> mkdir \HELLO

2 . Fr om Window s, double -click on t he Micr osoft Visual C+ + t o st ar t t he I DE. Clear ou t an y old j u n k by select in g t h e Win dow | Close All m en u it em . A blan k w or k space w ill be display ed as seen in Figure 2 -2 0 .

Figur e 2 - 2 0 . M icr osoft Visu a l C+ + in it ia l scr e e n

(48)

47

Figur e 2 - 2 1 . N e w Pr oj e ct dia log

Fil l in t he Pr oj ect Nam e blank w it h " \ hello \h ello. m ak " . Ch an ge t h e Pr oj ect Ty p e t o Quick Win applicat ion ( . EXE).

4 . Visu al C+ + goes t o t h e Edit dialog t o allow y ou t o n am e t h e sou r ce f iles in t h is pr oj ect ( see Figure 2 -2 2 ) . I n t h is case, w e h av e on ly f ile h ello. c. Click on

Add t o pu t t h is in t h e pr oj ect an d Close t o t ell Visu al C+ + t h at t h er e ar e n o m or e files in t he pr ogr am .

(49)

Figur e 2 - 2 2 . Edit Pr oj e ct dia log

5 . Select t h e Opt ions| Pr oj ect Opt ions m enu it em t o br ing up t he Pr oj ect Opt ions dialog as seen in Figure 2 -2 3 .

Figur e 2 - 2 3 . Pr oj e ct Opt ion s dia log

(50)

49

6 . Go dow n t o t h e Cust om Opt ions m en u it em u n der Cat eg or y and change t he

Warning Level t o 4 as seen in Figur e 2 -2 4 .

Figur e 2 - 2 4 . C/ C+ + Com pile r Opt ion s dia log

7 . Select t h e Mem or y Model cat eg or y an d ch an g e t h e Model t o Lar g e ( see Figure 2 -2 5 ) .

Figur e 2 - 2 5 . M e m or y M ode l opt ions

(51)

8 . Close t h e dialog by click in g on t h e OK bu t t on . You r et u r n t o t h e Pr oj ect Opt ion s dialog. Click on OK t o dism iss t his dialog as w ell.

9 . Select t h e File| New m enu it em t o st ar t a new pr ogr am file. Ty pe in Ex am ple 2 -4 .

Ex a m ple 2- 4 .

hello/ hello.c

[File: hello/hello.c] #include <stdio.h> int main()

{

printf("Hello World\n"); return (0);

}

Your r esult s should look Figur e 2 -2 6 .

Figur e 2 - 2 6 . M icr osoft Visua l C+ + w it h H e llo

W or ld e nt e r e d

1 0 .Use t h e File| Save As m en u it em t o sav e t h e f ile u n d er t h e n am e hello.c. 1 1 .Use t h e Pr oj ect | Build m enu it em t o com pile t he pr ogr am . The com piler w ill

(52)

51

Figur e 2 - 2 7 . M icr osoft Visu a l C+ + pr oj e ct bu ild

scr e e n

1 2 .Th e pr ogr am can n ow b e st ar t ed w it h t h e Debu g| Go m en u it em . Th e r esu lt s appear in Figur e 2 -2 8 .

Figur e 2 - 2 8 . H e llo W or ld r e sult s

(53)

2 . 5 Ge t t in g H e lp on U N I X

Most UN

Gambar

Figure 2 - 1. Transform ation of a high- level language
Figure 2 -4. Entry/ Exit Code Generation dialog
Figure 2 -6 . Open Project File dialog
Figure 2 -1 1 . Borland C+ +  initial screen
+7

Referensi

Dokumen terkait

Pada hari ini Senin tanggal Tiga Belas bulan Agustus tahun Dua Ribu Dua Belas , kami yang bertandatangan di bawah ini Panitia Pangadaan Barang dan Jasa Konstruksi Dinas Tata

2016 telah melaksanakan rapat penetapan pemenang terhadap Paket Pekerjaan Pengadaan Pembangunan Sisfo Data Bahan dan Produk Kajian Wantannas melalui pelelangan umum pasca

Universitas

mempersiapkan karir. Kualitas pemilihan karir ditentukan oleh tingkat kematangan karir. Harga diri dan motivasi berprestasi merupakan faktor personal yang terkait

Hal-hal tersebut sudah menjadi tradisi yang dilakukan masyarakat Jawa dalam kehidupan sehari-hari bertujuan supaya kehidupan mereka penuh dengan keberkahan dan

Diberitahukan dengan hormat, bahwa dalam proses pelaksanaan lelang pekerjaan Pembangunan Gedung PONEK RSUD Kota Madiun (Kode lelang 62164), telah terjadi masalah berupa

Kepala Balatrans Makassar selaku KPA (sebagai

Hal ini sesuai dengan nilai TI yang telah dibahas pada bagian sebelumnya yaitu TI digunakan untuk menciptakan nilai agar meningkatkan pertumbuhan bisnis dan