Tải bản đầy đủ - 0 (trang)
Appendix E. C Legacy Code Topics

Appendix E. C Legacy Code Topics

Tải bản đầy đủ - 0trang

AppendixE.CLegacyCodeTopics

We'lluseasignalIhavetriedandfoundfarreachingandeasytoyell.Waa-hoo!

ZaneGrey

Itisquiteathree-pipeproblem.

SirArthurConanDoyle

Butyetanunioninpartition.

WilliamShakespeare

OBJECTIVES

Inthischapteryouwilllearn:

Toredirectkeyboardinputtocomefromafileandredirect

screenoutputtoafile.

Towritefunctionsthatusevariable-lengthargumentlists.

Toprocesscommand-linearguments.

Toprocessunexpectedeventswithinaprogram.

Toallocatememorydynamicallyforarrays,usingC-style

dynamicmemoryallocation.

Toresizememorydynamicallyallocated,usingC-style

dynamicmemoryallocation.



[Page1248]

Outline

E.1Introduction

E.2RedirectingInput/OutputonUNIX/LINUX/MacOSX

andWindowsSystems

E.3Variable-LengthArgumentLists

E.4UsingCommand-LineArguments

E.5NotesonCompilingMultiple-Source-FilePrograms

E.6ProgramTerminationwithexitandatexit

E.7ThevolatileTypeQualifier

E.8SuffixesforIntegerandFloating-PointConstants

E.9SignalHandling

E.10DynamicMemoryAllocationwithcallocandrealloc

E.11TheUnconditionalBranch:goto

E.12Unions

E.13LinkageSpecifications

E.14Wrap-Up

Summary



Terminology

Self-ReviewExercises

AnswerstoSelf-ReviewExercises

Exercises







[Page1248(continued)]



E.1.Introduction

Thischapterpresentsseveraltopicsnotordinarilycoveredin

introductorycourses.Manyofthecapabilitiesdiscussedhere

arespecifictoparticularoperatingsystems,especially

UNIX/LINUX/MacOSXand/orWindows.Muchofthematerialis

forthebenefitofC++programmerswhowillneedtoworkwith

olderClegacycode.







[Page1248(continued)]



E.2.RedirectingInput/Outputon

UNIX/LINUX/MacOSXandWindowsSystems

Normally,theinputtoaprogramisfromthekeyboard

(standardinput),andtheoutputfromaprogramisdisplayedon

thescreen(standardoutput).OnmostcomputersystemsUNIX,

LINUX,MacOSXandWindowssystemsinparticularitis

possibletoredirectinputstocomefromafile,andredirect

outputstobeplacedinafile.Bothformsofredirectioncanbe

accomplishedwithoutusingthefile-processingcapabilitiesof

thestandardlibrary.

Thereareseveralwaystoredirectinputandoutputfromthe

UNIXcommandline.Considertheexecutablefilesumthatinputs

integersoneatatime,keepsarunningtotalofthevaluesuntil

theend-of-fileindicatorisset,thenprintstheresult.Normally

theuserinputsintegersfromthekeyboardandenterstheendof-filekeycombinationtoindicatethatnofurthervalueswillbe

input.Withinputredirection,theinputcanbestoredinafile.

Forexample,ifthedataarestoredinfileinput,thecommand

line

$sum


causesprogramsumtobeexecuted;theredirectinput

symbol(<)indicatesthatthedatainfileinput(insteadofthe

keyboard)istobeusedasinputbytheprogram.Redirecting

inputinaWindowsCommandPromptisperformedidentically.



[Page1249]

Notethat$representstheUNIXcommand-lineprompt.(UNIX



promptsvaryfromsystemtosystemandbetweenshellsona

singlesystem.)Redirectionisanoperating-systemfunction,not

anotherC++feature.

Thesecondmethodofredirectinginputispiping.Apipe(|)

causestheoutputofoneprogramtoberedirectedastheinput

toanotherprogram.Supposeprogramrandomoutputsaseriesof

randomintegers;theoutputofrandomcanbe"piped"directlyto

programsumusingtheUNIXcommandline

$random|sum



Thiscausesthesumoftheintegersproducedbyrandomtobe

calculated.PipingcanbeperformedinUNIX,LINUX,MacOSX

andWindows.

Programoutputcanberedirectedtoafilebyusingthe

redirectoutputsymbol(>).(Thesamesymbolisusedfor

UNIX,LINUX,MacOSXandWindows.)Forexample,toredirect

theoutputofprogramrandomtoanewfilecalledout,use

$random>out



Finally,programoutputcanbeappendedtotheendofan

existingfilebyusingtheappendoutputsymbol(>>).(The

samesymbolisusedforUNIX,LINUX,MacOSXandWindows.)

Forexample,toappendtheoutputfromprogramrandomtofile

outcreatedintheprecedingcommandline,usethecommand

line

$random>>out



[Page1249(continued)]



E.3.Variable-LengthArgumentLists[1]

[1]InC++,programmersusefunctionoverloadingtoaccomplishmuchofwhatCprogrammersaccomplishwith

variable-lengthargumentlists.



Itispossibletocreatefunctionsthatreceiveanunspecified

numberofarguments.Anellipsis(...)inafunction'sprototype

indicatesthatthefunctionreceivesavariablenumberof

argumentsofanytype.Notethattheellipsismustalwaysbe

placedattheendoftheparameterlist,andtheremustbeat

leastoneargumentbeforetheellipsis.Themacrosand

definitionsofthevariableargumentsheader(Fig.

E.1)providethecapabilitiesnecessarytobuildfunctionswith

variable-lengthargumentlists.

FigureE.1.Thetypeandthemacrosdefinedinheader

.

(Thisitemisdisplayedonpage1250intheprintversion)

Identifier



Description



va_list



Atypesuitableforholdinginformationneededby

macrosva_start,va_argandva_end.Toaccessthe

argumentsinavariable-lengthargumentlist,anobject

oftypeva_listmustbedeclared.



va_start



Amacrothatisinvokedbeforetheargumentsofa

variable-lengthargumentlistcanbeaccessed.The

macroinitializestheobjectdeclaredwithva_listforuse

bytheva_argandva_endmacros.



va_arg



Amacrothatexpandstoanexpressionofthevalueand

typeofthenextargumentinthevariable-length

argumentlist.Eachinvocationofva_argmodifiesthe

objectdeclaredwithva_listsothattheobjectpointsto

thenextargumentinthelist.



va_end



Amacrothatperformsterminationhousekeepingina

functionwhosevariable-lengthargumentlistwas

referredtobytheva_startmacro.



FigureE.2demonstratesfunctionaveragethatreceivesavariable

numberofarguments.Thefirstargumentofaverageisalways

thenumberofvaluestobeaveraged,andtheremainderofthe

argumentsmustallbeoftypedouble.



FigureE.2.Usingvariable-lengthargumentlists.

(Thisitemisdisplayedonpages1250-1251intheprint

version)



1//Fig.E.2:figE_02.cpp

2//Usingvariable-lengthargumentlists.

3#include

4usingstd::cout;

5usingstd::endl;

6usingstd::ios;

7

8#include

9usingstd::setw;

10usingstd::setprecision;

11usingstd::setiosflags;

12usingstd::fixed;

13

14#include

15usingstd::va_list;

16

17doubleaverage(int,...);

18

19intmain()

20{

21doubledouble1=37.5;

22doubledouble2=22.5;

23doubledouble3=1.7;

24doubledouble4=10.2;

25

26cout<
27<
28<
29<
30<<"\nTheaverageofdouble1anddouble2is"

31<
32<<"\nTheaverageofdouble1,double2,anddouble3is"

33<


34<<"\nTheaverageofdouble1,double2,double3"

35<<"anddouble4is"

36<
37<
38return0;

39}//endmain

40

41//calculateaverage

42doubleaverage(intcount,...)

43{

44doubletotal=0;

45va_listlist;//forstoringinformationneededbyva_start

46

47va_start(list,count);

48

49//processvariable-lengthargumentlist

50for(inti=1;i<=count;i++)

51total+=va_arg(list,double);

52

53va_end(list);//endtheva_start

54returntotal/count;

55}//endfunctionaverage



double1=37.5

double2=22.5

double3=1.7

double4=10.2

Theaverageofdouble1anddouble2is30.000

Theaverageofdouble1,double2,anddouble3is20.567

Theaverageofdouble1,double2,double3anddouble4is17.975



Functionaverageusesallthedefinitionsandmacrosofheader

.Objectlist,oftypeva_list,isusedbymacrosva_start,

va_argandva_endtoprocessthevariable-lengthargumentlistof

functionaverage.Thefunctioninvokesva_starttoinitializeobject

listforuseinva_argandva_end.Themacroreceivestwo

argumentsobjectlistandtheidentifieroftherightmost

argumentintheargumentlistbeforetheellipsiscountinthis



case(va_startusescountheretodeterminewherethevariablelengthargumentlistbegins).

Next,functionaveragerepeatedlyaddstheargumentsinthe

variable-lengthargumentlisttothetotal.Thevaluetobeadded

tototalisretrievedfromtheargumentlistbyinvokingmacro

va_arg.Macrova_argreceivestwoargumentsobjectlistandthe

typeofthevalueexpectedintheargumentlist(doubleinthis

case)andreturnsthevalueoftheargument.Functionaverage

invokesmacrova_endwithobjectlistasanargumentbefore

returning.Finally,theaverageiscalculatedandreturnedtomain.

Notethatweusedonlydoubleargumentsforthevariable-length

portionoftheargumentlist.



[Page1251]

Variable-lengthargumentlistspromotevariablesoftypefloatto

typedouble.Theseargumentlistsalsopromoteintegralvariables

thataresmallerthaninttotypeint(variablesoftypeint,

unsigned,longandunsignedlongareleftalone).



SoftwareEngineeringObservationE.1

Variable-lengthargumentlistscanbeusedonlywith

fundamentaltypeargumentsandwithargumentsofCstylestructtypesthatdonotcontainC++specific

featuressuchasvirtualfunctions,constructors,

destructors,references,constdatamembersandvirtual

baseclasses.



[Page1252]

CommonProgrammingErrorE.1



Placinganellipsisinthemiddleofafunctionparameter

listisasyntaxerror.Anellipsismaybeplacedonlyat

theendoftheparameterlist.







Tài liệu bạn tìm kiếm đã sẵn sàng tải về

Appendix E. C Legacy Code Topics

Tải bản đầy đủ ngay(0 tr)

×