Tải bản đầy đủ - 0 (trang)
Chapter 2.  Variables and Basic Types

Chapter 2.  Variables and Basic Types

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

usesthesemechanismstodefinemorecomplextypessuchas

variable-lengthcharacterstrings,vectors,andsoon.Finally,we

canmodifyexistingtypestoformcompoundtypes.Thischapter

coversthebuilt-intypesandbeginsourcoverageofhowC++

supportsmorecomplicatedtypes.

Typesdeterminewhatthedataandoperationsinour

programsmean.AswesawinChapter1,thesamestatement

i=i+j;



canmeandifferentthingsdependingonthetypesofiandj.If

iandjareintegers,thenthisstatementhastheordinary,

arithmeticmeaningof+.However,ifiandjareSales_item

objects,thenthisstatementaddsthecomponentsofthesetwo

objects.

InC++thesupportfortypesisextensive:Thelanguageitself

definesasetofprimitivetypesandwaysinwhichwecan

modifyexistingtypes.Italsoprovidesasetoffeaturesthat

allowustodefineourowntypes.Thischapterbeginsour

explorationoftypesinC++bycoveringthebuilt-intypesand

showinghowweassociateatypewithanobject.Italso

introduceswayswecanbothmodifytypesandcanbuildour

owntypes.



2.1.PrimitiveBuilt-inTypes

C++definesasetofarithmetictypes,whichrepresent

integers,floating-pointnumbers,andindividualcharactersand

booleanvalues.Inaddition,thereisaspecialtypenamedvoid.

Thevoidtypehasnoassociatedvaluesandcanbeusedinonly

alimitedsetofcircumstances.Thevoidtypeismostoftenused

asthereturntypeforafunctionthathasnoreturnvalue.

Thesizeofthearithmetictypesvariesacrossmachines.Bysize,

wemeanthenumberofbitsusedtorepresentthetype.The

standardguaranteesaminimumsizeforeachofthearithmetic

types,butitdoesnotpreventcompilersfromusinglargersizes.

Indeed,almostallcompilersusealargersizeforintthanis

strictlyrequired.Table2.1(p.36)liststhebuilt-inarithmetic

typesandtheassociatedminimumsizes.

Table2.1.C++:ArithmeticTypes

Type



Meaning



MinimumSize



bool



boolean



NA



char



character



8bits



wchar_t



widecharacter



16bits



short



shortinteger



16bits



int



integer



16bits



long



longinteger



32bits



float



single-precisionfloatingpoint



6significantdigits



double



double-precisionfloating-



10significantdigits



point

longdouble



extended-precisionfloating- 10significantdigits

point



Becausethenumberofbitsvaries,themaximum(or

minimum)valuesthatthesetypescanrepresentalsovary

bymachine.



2.1.1.IntegralTypes

Thearithmetictypesthatrepresentintegers,characters,and

booleanvaluesarecollectivelyreferredtoastheintegral

types.

Therearetwocharactertypes:charandwchar_t.Thechartypeis

guaranteedtobebigenoughtoholdnumericvaluesthat

correspondtoanycharacterinthemachine'sbasiccharacter

set.Asaresult,charsareusuallyasinglemachinebyte.The

wchar_ttypeisusedforextendedcharactersets,suchasthose

usedforChineseandJapanese,inwhichsomecharacters

cannotberepresentedwithinasinglechar.

Thetypesshort,int,andlongrepresentintegervaluesof

potentiallydifferentsizes.Typically,shortsarerepresentedin

halfamachineword,intsinamachineword,andlongsineither

oneortwomachinewords(on32-bitmachines,intsandlongs



areusuallythesamesize).



Machine-LevelRepresentationofTheBuilt-inTypes

TheC++built-intypesarecloselytiedtotheirrepresentationinthe

computer'smemory.Computersstoredataasasequenceofbits,eachof

whichholdseither0or1.Asegmentofmemorymighthold

00011011011100010110010000111011...



Atthebitlevel,memoryhasnostructureandnomeaning.

Themostprimitivewayweimposestructureonmemoryisby

processingitinchunks.Mostcomputersdealwithmemoryaschunksof

bitsofparticularsizes,usuallypowersof2.Theyusuallymakeiteasyto

process8,16,or32bitsatatime,andchunksof64and128bitsare

becomingmorecommon.Althoughtheexactsizescanvaryfromone

machinetoanother,weusuallyrefertoachunkof8bitsasa"byte"and

32bits,or4bytes,asa"word."

Mostcomputersassociateanumbercalledanaddresswitheachbytein

memory.Givenamachinethathas8-bitbytesand32-bitwords,we

mightrepresentawordofmemoryasfollows:



736424



0



0



0



1



1



0



1



1



736425



0



1



1



1



0



0



0



1



736426



0



1



1



0



0



1



0



0



736427



0



0



1



1



1



0



1



1



Inthisillustration,eachbyte'saddressisshownontheleft,withthe8

bitsofthebytefollowingtheaddress.

Wecanuseanaddresstorefertoanyofseveralvariouslysized

collectionsofbitsstartingatthataddress.Itispossibletospeakofthe

wordataddress736424orthebyteataddress736426.Wecansay,for

example,thatthebyteataddress736425isnotequaltothebyteat

address736427.

Togivemeaningtothebyteataddress736425,wemustknowthetype

ofthevaluestoredthere.Onceweknowthetype,weknowhowmany



bitsareneededtorepresentavalueofthattypeandhowtointerpret

thosebits.

Ifweknowthatthebyteatlocation736425hastype"unsigned8-bit

integer,"thenweknowthatthebyterepresentsthenumber112.Onthe

otherhand,ifthatbyteisacharacterintheISO-Latin-1characterset,

thenitrepresentsthelower-caseletterq.Thebitsarethesameinboth

cases,butbyascribingdifferenttypestothem,weinterpretthem

differently.



Thetypeboolrepresentsthetruthvalues,trueandfalse.Wecan

assignanyofthearithmetictypestoabool.Anarithmetictype

withvalue0yieldsaboolthatholdsfalse.Anynonzerovalueis

treatedasTRue.



SignedandUnsignedTypes

Theintegraltypes,exceptthebooleantype,maybeeither

signedorunsigned.Asitsnamesuggests,asignedtypecan

representbothnegativeandpositivenumbers(includingzero),

whereasanunsignedtyperepresentsonlyvaluesgreaterthanor

equaltozero.

Theintegers,int,short,andlong,areallsignedbydefault.To

getanunsignedtype,thetypemustbespecifiedasunsigned,

suchasunsignedlong.Theunsignedinttypemaybeabbreviated

asunsigned.Thatis,unsignedwithnoothertypeimpliesunsigned

int.

Unliketheotherintegraltypes,therearethreedistincttypesfor

char:plainchar,signedchar,andunsignedchar.Althoughthereare

threedistincttypes,thereareonlytwowaysacharcanbe

represented.Thechartypeisrespresentedusingeitherthe

signedcharorunsignedcharversion.Whichrepresentationisused

forcharvariesbycompiler.



HowIntegralValuesAreRepresented

Inanunsignedtype,allthebitsrepresentthevalue.Ifatypeis

definedforaparticularmachinetouse8bits,thentheunsigned

versionofthistypecouldholdthevalues0through255.

TheC++standarddoesnotdefinehowsignedtypesare

representedatthebitlevel.Instead,eachcompilerisfreeto

decidehowitwillrepresentsignedtypes.Theserepresentations

canaffecttherangeofvaluesthatasignedtypecanhold.We

areguaranteedthatan8-bitsignedtypewillholdatleastthe

valuesfrom127through127;manyimplementationsallow

valuesfrom128through127.

Underthemostcommonstrategyforrepresentingsigned

integraltypes,wecanviewoneofthebitsasasignbit.

Wheneverthesignbitis1,thevalueisnegative;whenitis0,

thevalueiseither0orapositivenumber.An8-bitintegral

signedtyperepresentedusingasign-bitcanholdvaluesfrom

128through127.



AssignmenttoIntegralTypes

Thetypeofanobjectdeterminesthevaluesthattheobjectcan

hold.Thisfactraisesthequestionofwhathappenswhenone

triestoassignavalueoutsidetheallowablerangetoanobject

ofagiventype.Theanswerdependsonwhetherthetypeis

signedorunsigned.

Forunsignedtypes,thecompilermustadjusttheout-of-range

valuesothatitwillfit.Thecompilerdoessobytakingthe

remainderofthevaluemodulothenumberofdistinctvalues

theunsignedtargettypecanhold.Anobjectthatisan8-bit

unsignedchar,forexample,canholdvaluesfrom0through255

inclusive.Ifweassignavalueoutsidethisrange,thecompiler

actuallyassignstheremainderofthevaluemodulo256.For



example,wemightattempttoassignthevalue336toan8-bit

signedchar.Ifwetrytostore336inour8-bitunsignedchar,the

actualvalueassignedwillbe80,because80isequalto336

modulo256.

Fortheunsignedtypes,anegativevalueisalwaysoutofrange.

Anobjectofunsignedtypemayneverholdanegativevalue.

Somelanguagesmakeitillegaltoassignanegativevaluetoan

unsignedtype,butC++doesnot.

InC++itisperfectlylegaltoassignanegativenumberto

anobjectwithunsignedtype.Theresultisthenegative

valuemodulothesizeofthetype.So,ifweassign1toan

8-bitunsignedchar,theresultingvaluewillbe255,whichis

1modulo256.



Whenassigninganout-of-rangevaluetoasignedtype,itisup

tothecompilertodecidewhatvaluetoassign.Inpractice,

manycompilerstreatsignedtypessimilarlytohowtheyare

requiredtotreatunsignedtypes.Thatis,theydotheassignment

astheremaindermodulothesizeofthetype.However,weare

notguaranteedthatthecompilerwilldosoforthesignedtypes.



2.1.2.Floating-PointTypes

Thetypesfloat,double,andlongdoublerepresentfloating-point

single-,double-,andextended-precisionvalues.Typically,floats

arerepresentedinoneword(32bits),doublesintwowords(64

bits),andlongdoubleineitherthreeorfourwords(96or128

bits).Thesizeofthetypedeterminesthenumberofsignificant

digitsafloating-pointvaluemightcontain.



Thefloattypeisusuallynotpreciseenoughforreal

programsfloatisguaranteedtoofferonly6significant

digits.Thedoubletypeguaranteesatleast10significant

digits,whichissufficientformostcalculations.



2.2.LiteralConstants

Avalue,suchas42,inaprogramisknownasaliteral

constant:literalbecausewecanspeakofitonlyintermsofits

value;constantbecauseitsvaluecannotbechanged.Every

literalhasanassociatedtype.Forexample,0isanintand

3.14159isadouble.Literalsexistonlyforthebuilt-intypes.There

arenoliteralsofclasstypes.Hence,therearenoliteralsofany

ofthelibrarytypes.



Advice:UsingtheBuilt-inArithmeticTypes

ThenumberofintegraltypesinC++canbebewildering.C++,likeC,is

designedtoletprogramsgetclosetothehardwarewhennecessary,and

theintegraltypesaredefinedtocatertothepeculiaritiesofvarious

kindsofhardware.Mostprogrammerscan(andshould)ignorethese

complexitiesbyrestrictingthetypestheyactuallyuse.

Inpractice,manyusesofintegersinvolvecounting.Forexample,

programsoftencountthenumberofelementsinadatastructuresuch

asavectororanarray.We'llseeinChapters3and4thatthelibrary

definesasetoftypestousewhendealingwiththesizeofanobject.

Whencountingsuchelementsitisalwaysrighttousethelibrarydefinedtypeintendedforthispurpose.Whencountinginother

circumstances,itisusuallyrighttouseanunsignedvalue.Doingsoavoids

thepossibilitythatavaluethatistoolargetofitresultsina(seemingly)

negativeresult.

Whenperformingintegerarithmetic,itisrarelyrighttouseshorts.In

mostprograms,usingshortsleadstomysteriousbugswhenavalueis

assignedtoashortthatisbiggerthanthelargestnumberitcanhold.

Whathappensdependsonthemachine,buttypicallythevalue"wraps

around"sothatanumbertoolargetofitturnsintoalargenegative

number.Forthesamereason,eventhoughcharisanintegraltype,the

chartypeshouldbeusedtoholdcharactersandnotforcomputation.The

factthatcharissignedonsomeimplementationsandunsignedonothers

makesitproblematictouseitasacomputationaltype.

Onmostmachines,integercalculationscansafelyuseint.Technically

speaking,anintcanbeassmallas16bitstoosmallformostpurposes.

Inpractice,almostallgeneral-purposemachinesuse32-bitsforints,

whichisoftenthesamesizeusedforlong.Thedifficultyindeciding

whethertouseintorlongoccursonmachinesthathave32-bitintsand

64-bitlongs.Onsuchmachines,therun-timecostofdoingarithmetic

withlongscanbeconsiderablygreaterthandoingthesamecalculation

usinga32-bitint.Decidingwhethertouseintorlongrequiresdetailed

understandingoftheprogramandtheactualrun-timeperformancecost

ofusinglongversusint.

Determiningwhichfloating-pointtypetouseiseasier:Itisalmost

alwaysrighttousedouble.Thelossofprecisionimplicitinfloatis

significant,whereasthecostofdoubleprecisioncalculationsversus

singleprecisionisnegligible.Infact,onsomemachines,double

precisionisfasterthansingle.Theprecisionofferedbylongdoubleusually

isunnecessaryandoftenentailsconsiderableextrarun-timecost.



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

Chapter 2.  Variables and Basic Types

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

×