Sei sulla pagina 1di 4

8/5/2015 VariablesandtypesC++Tutorials

Search: Go
Notloggedin

Tutorials C++Language Variablesandtypes register login

C++
Information
Tutorials
Reference
Articles
Forum

Tutorials Variablesandtypes
C++Language Theusefulnessofthe"HelloWorld"programsshowninthepreviouschapterisratherquestionable.Wehadtowrite
AsciiCodes severallinesofcode,compilethem,andthenexecutetheresultingprogram,justtoobtaintheresultofasimple
BooleanOperations sentencewrittenonthescreen.Itcertainlywouldhavebeenmuchfastertotypetheoutputsentenceourselves.
NumericalBases
However,programmingisnotlimitedonlytoprintingsimpletextsonthescreen.Inordertogoalittlefurtheronandto
C++Language becomeabletowriteprogramsthatperformusefultasksthatreallysaveuswork,weneedtointroducetheconceptof
Introduction: variable.
Compilers
BasicsofC++: Let'simaginethatIaskyoutorememberthenumber5,andthenIaskyoutoalsomemorizethenumber2atthesame
Structureofaprogram time.Youhavejuststoredtwodifferentvaluesinyourmemory(5and2).Now,ifIaskyoutoadd1tothefirstnumberI
Variablesandtypes said,youshouldberetainingthenumbers6(thatis5+1)and2inyourmemory.Thenwecould,forexample,subtract
Constants thesevaluesandobtain4asresult.
Operators
Thewholeprocessdescribedaboveisasimileofwhatacomputercandowithtwovariables.Thesameprocesscanbe
BasicInput/Output
expressedinC++withthefollowingsetofstatements:
Programstructure:
Statementsandflowcontrol
1 a=5;
Functions
2 b=2;
Overloadsandtemplates 3 a=a+1;
Namevisibility 4 result=ab;
Compounddatatypes:
Arrays
Charactersequences Obviously,thisisaverysimpleexample,sincewehaveonlyusedtwosmallintegervalues,butconsiderthatyour
Pointers computercanstoremillionsofnumbersliketheseatthesametimeandconductsophisticatedmathematicaloperations
Dynamicmemory withthem.
Datastructures
Otherdatatypes Wecannowdefinevariableasaportionofmemorytostoreavalue.
Classes:
Classes(I) Eachvariableneedsanamethatidentifiesitanddistinguishesitfromtheothers.Forexample,inthepreviouscodethe
Classes(II) variablenameswerea,b,andresult,butwecouldhavecalledthevariablesanynameswecouldhavecomeupwith,as
Specialmembers longastheywerevalidC++identifiers.
Friendshipandinheritance
Polymorphism
Otherlanguagefeatures: Identifiers
Typeconversions Avalididentifierisasequenceofoneormoreletters,digits,orunderscorecharacters(_).Spaces,punctuationmarks,
Exceptions andsymbolscannotbepartofanidentifier.Inaddition,identifiersshallalwaysbeginwithaletter.Theycanalsobegin
Preprocessordirectives withanunderlinecharacter(_),butsuchidentifiersareonmostcasesconsideredreservedforcompilerspecific
Standardlibrary: keywordsorexternalidentifiers,aswellasidentifierscontainingtwosuccessiveunderscorecharactersanywhere.Inno
Input/outputwithfiles casecantheybeginwithadigit.

C++usesanumberofkeywordstoidentifyoperationsanddatadescriptionstherefore,identifierscreatedbya
programmercannotmatchthesekeywords.Thestandardreservedkeywordsthatcannotbeusedforprogrammer
createdidentifiersare:

alignas,alignof,and,and_eq,asm,auto,bitand,bitor,bool,break,case,catch,char,char16_t,char32_t,
class,compl,const,constexpr,const_cast,continue,decltype,default,delete,do,double,dynamic_cast,
else,enum,explicit,export,extern,false,float,for,friend,goto,if,inline,int,long,mutable,
namespace,new,noexcept,not,not_eq,nullptr,operator,or,or_eq,private,protected,public,register,
reinterpret_cast,return,short,signed,sizeof,static,static_assert,static_cast,struct,switch,template,
this,thread_local,throw,true,try,typedef,typeid,typename,union,unsigned,using,virtual,void,
volatile,wchar_t,while,xor,xor_eq

Specificcompilersmayalsohaveadditionalspecificreservedkeywords.

Veryimportant:TheC++languageisa"casesensitive"language.Thatmeansthatanidentifierwrittenincapital
lettersisnotequivalenttoanotheronewiththesamenamebutwritteninsmallletters.Thus,forexample,theRESULT
variableisnotthesameastheresultvariableortheResultvariable.Thesearethreedifferentidentifiersidentifiying
threedifferentvariables.

Fundamentaldatatypes
Thevaluesofvariablesarestoredsomewhereinanunspecifiedlocationinthecomputermemoryaszerosandones.Our
programdoesnotneedtoknowtheexactlocationwhereavariableisstoreditcansimplyrefertoitbyitsname.What
theprogramneedstobeawareofisthekindofdatastoredinthevariable.It'snotthesametostoreasimpleintegeras
itistostorealetteroralargefloatingpointnumbereventhoughtheyareallrepresentedusingzerosandones,they
arenotinterpretedinthesameway,andinmanycases,theydon'toccupythesameamountofmemory.

Fundamentaldatatypesarebasictypesimplementeddirectlybythelanguagethatrepresentthebasicstorageunits
supportednativelybymostsystems.Theycanmainlybeclassifiedinto:

Charactertypes:Theycanrepresentasinglecharacter,suchas'A'or'$'.Themostbasictypeischar,whichis
aonebytecharacter.Othertypesarealsoprovidedforwidercharacters.
Numericalintegertypes:Theycanstoreawholenumbervalue,suchas7or1024.Theyexistinavarietyof
sizes,andcaneitherbesignedorunsigned,dependingonwhethertheysupportnegativevaluesornot.
Floatingpointtypes:Theycanrepresentrealvalues,suchas3.14or0.01,withdifferentlevelsofprecision,
dependingonwhichofthethreefloatingpointtypesisused.
Booleantype:Thebooleantype,knowninC++asbool,canonlyrepresentoneoftwostates,trueorfalse.

HereisthecompletelistoffundamentaltypesinC++:
Group Typenames* Notesonsize/precision
char Exactlyonebyteinsize.Atleast8bits.

http://www.cplusplus.com/doc/tutorial/variables/ 1/4
8/5/2015 VariablesandtypesC++Tutorials
Charactertypes char16_t Notsmallerthanchar.Atleast16bits.
char32_t Notsmallerthanchar16_t.Atleast32bits.
wchar_t Canrepresentthelargestsupportedcharacterset.
signedchar Samesizeaschar.Atleast8bits.
signedshortint Notsmallerthanchar.Atleast16bits.
Integertypes(signed) signedint Notsmallerthanshort.Atleast16bits.
signedlongint Notsmallerthanint.Atleast32bits.
signedlonglongint Notsmallerthanlong.Atleast64bits.
unsignedchar
unsignedshortint
Integertypes(unsigned) unsignedint (samesizeastheirsignedcounterparts)
unsignedlongint
unsignedlonglongint
float
Floatingpointtypes double Precisionnotlessthanfloat
longdouble Precisionnotlessthandouble
Booleantype bool
Voidtype void nostorage
Nullpointer decltype(nullptr)

*Thenamesofcertainintegertypescanbeabbreviatedwithouttheirsignedandintcomponentsonlythepartnotin
italicsisrequiredtoidentifythetype,thepartinitalicsisoptional.I.e.,signedshortintcanbeabbreviatedassigned
short,shortint,orsimplyshorttheyallidentifythesamefundamentaltype.

Withineachofthegroupsabove,thedifferencebetweentypesisonlytheirsize(i.e.,howmuchtheyoccupyinmemory):
thefirsttypeineachgroupisthesmallest,andthelastisthelargest,witheachtypebeingatleastaslargeastheone
precedingitinthesamegroup.Otherthanthat,thetypesinagrouphavethesameproperties.

Noteinthepanelabovethatotherthanchar(whichhasasizeofexactlyonebyte),noneofthefundamentaltypeshasa
standardsizespecified(butaminimumsize,atmost).Therefore,thetypeisnotrequired(andinmanycasesisnot)
exactlythisminimumsize.Thisdoesnotmeanthatthesetypesareofanundeterminedsize,butthatthereisno
standardsizeacrossallcompilersandmachineseachcompilerimplementationmayspecifythesizesforthesetypesthat
fitthebestthearchitecturewheretheprogramisgoingtorun.Thisrathergenericsizespecificationfortypesgivesthe
C++languagealotofflexibilitytobeadaptedtoworkoptimallyinallkindsofplatforms,bothpresentandfuture.

Typesizesaboveareexpressedinbitsthemorebitsatypehas,themoredistinctvaluesitcanrepresent,butatthe
sametime,alsoconsumesmorespaceinmemory:

Size Uniquerepresentablevalues Notes


8bit 256 =2 8
16bit 65536 =2 16
32bit 4294967296 =2 32(~4billion)
64bit 18446744073709551616 =2 64(~18billionbillion)

Forintegertypes,havingmorerepresentablevaluesmeansthattherangeofvaluestheycanrepresentisgreaterfor
example,a16bitunsignedintegerwouldbeabletorepresent65536distinctvaluesintherange0to65535,whileits
signedcounterpartwouldbeabletorepresent,onmostcases,valuesbetween32768and32767.Notethattherange
ofpositivevaluesisapproximatelyhalvedinsignedtypescomparedtounsignedtypes,duetothefactthatoneofthe16
bitsisusedforthesignthisisarelativelymodestdifferenceinrange,andseldomjustifiestheuseofunsignedtypes
basedpurelyontherangeofpositivevaluestheycanrepresent.

Forfloatingpointtypes,thesizeaffectstheirprecision,byhavingmoreorlessbitsfortheirsignificantandexponent.

Ifthesizeorprecisionofthetypeisnotaconcern,thenchar,int,anddoublearetypicallyselectedtorepresent
characters,integers,andfloatingpointvalues,respectively.Theothertypesintheirrespectivegroupsareonlyusedin
veryparticularcases.

Thepropertiesoffundamentaltypesinaparticularsystemandcompilerimplementationcanbeobtainedbyusingthe
numeric_limitsclasses(seestandardheader<limits>).Ifforsomereason,typesofspecificsizesareneeded,thelibrary
definescertainfixedsizetypealiasesinheader<cstdint>.

Thetypesdescribedabove(characters,integers,floatingpoint,andboolean)arecollectivelyknownasarithmetictypes.
Buttwoadditionalfundamentaltypesexist:void,whichidentifiesthelackoftypeandthetypenullptr,whichisa
specialtypeofpointer.Bothtypeswillbediscussedfurtherinacomingchapteraboutpointers.

C++supportsawidevarietyoftypesbasedonthefundamentaltypesdiscussedabovetheseothertypesareknownas
compounddatatypes,andareoneofthemainstrengthsoftheC++language.Wewillalsoseetheminmoredetailin
futurechapters.

Declarationofvariables
C++isastronglytypedlanguage,andrequireseveryvariabletobedeclaredwithitstypebeforeitsfirstuse.Thisinforms
thecompilerthesizetoreserveinmemoryforthevariableandhowtointerpretitsvalue.Thesyntaxtodeclareanew
variableinC++isstraightforward:wesimplywritethetypefollowedbythevariablename(i.e.,itsidentifier).For
example:

1 inta;
2 floatmynumber;

Thesearetwovaliddeclarationsofvariables.Thefirstonedeclaresavariableoftypeintwiththeidentifiera.Thesecond
onedeclaresavariableoftypefloatwiththeidentifiermynumber.Oncedeclared,thevariablesaandmynumbercanbeused
withintherestoftheirscopeintheprogram.
Ifdeclaringmorethanonevariableofthesametype,theycanallbedeclaredinasinglestatementbyseparatingtheir
identifierswithcommas.Forexample:

inta,b,c;

Thisdeclaresthreevariables(a,bandc),allofthemoftypeint,andhasexactlythesamemeaningas:

http://www.cplusplus.com/doc/tutorial/variables/ 2/4
8/5/2015 VariablesandtypesC++Tutorials

1 inta;
2 intb;
3 intc;

Toseewhatvariabledeclarationslooklikeinactionwithinaprogram,let'shavealookattheentireC++codeofthe
exampleaboutyourmentalmemoryproposedatthebeginningofthischapter:

1 //operatingwithvariables 4
2 Edit
3 #include<iostream>
4 usingnamespacestd;
5
6 intmain()
7 {
8 //declaringvariables:
9 inta,b;
10 intresult;
11
12 //process:
13 a=5;
14 b=2;
15 a=a+1;
16 result=ab;
17
18 //printouttheresult:
19 cout<<result;
20
21 //terminatetheprogram:
22 return0;
23 }

Don'tbeworriedifsomethingelsethanthevariabledeclarationsthemselveslookabitstrangetoyou.Mostofitwillbe
explainedinmoredetailincomingchapters.

Initializationofvariables
Whenthevariablesintheexampleabovearedeclared,theyhaveanundeterminedvalueuntiltheyareassignedavalue
forthefirsttime.Butitispossibleforavariabletohaveaspecificvaluefromthemomentitisdeclared.Thisiscalledthe
initializationofthevariable.

InC++,therearethreewaystoinitializevariables.Theyareallequivalentandarereminiscentoftheevolutionofthe
languageovertheyears:

Thefirstone,knownasclikeinitialization(becauseitisinheritedfromtheClanguage),consistsofappendinganequal
signfollowedbythevaluetowhichthevariableisinitialized:

typeidentifier=initial_value;
Forexample,todeclareavariableoftypeintcalledxandinitializeittoavalueofzerofromthesamemomentitis
declared,wecanwrite:

intx=0;

Asecondmethod,knownasconstructorinitialization(introducedbytheC++language),enclosestheinitialvalue
betweenparentheses(()):

typeidentifier(initial_value);
Forexample:

intx(0);

Finally,athirdmethod,knownasuniforminitialization,similartotheabove,butusingcurlybraces({})insteadof
parentheses(thiswasintroducedbytherevisionoftheC++standard,in2011):

typeidentifier{initial_value};
Forexample:

intx{0};

AllthreewaysofinitializingvariablesarevalidandequivalentinC++.

1 //initializationofvariables 6
2 Edit
3 #include<iostream>
4 usingnamespacestd;
5
6 intmain()
7 {
8 inta=5;//initialvalue:5
9 intb(3);//initialvalue:3
10 intc{2};//initialvalue:2
11 intresult;//initialvalueundetermined
12
13 a=a+b;
14 result=ac;
15 cout<<result;
16
17 return0;
18 }

http://www.cplusplus.com/doc/tutorial/variables/ 3/4
8/5/2015 VariablesandtypesC++Tutorials
Typededuction:autoanddecltype
Whenanewvariableisinitialized,thecompilercanfigureoutwhatthetypeofthevariableisautomaticallybythe
initializer.Forthis,itsufficestouseautoasthetypespecifierforthevariable:

1 intfoo=0;
2 autobar=foo;//thesameas:intbar=foo;

Here,barisdeclaredashavinganautotypetherefore,thetypeofbaristhetypeofthevalueusedtoinitializeit:inthis
caseitusesthetypeoffoo,whichisint.

Variablesthatarenotinitializedcanalsomakeuseoftypedeductionwiththedecltypespecifier:

1 intfoo=0;
2 decltype(foo)bar;//thesameas:intbar;

Here,barisdeclaredashavingthesametypeasfoo.

autoanddecltypearepowerfulfeaturesrecentlyaddedtothelanguage.Butthetypedeductionfeaturestheyintroduce
aremeanttobeusedeitherwhenthetypecannotbeobtainedbyothermeansorwhenusingitimprovescode
readability.Thetwoexamplesabovewerelikelyneitheroftheseusecases.Infacttheyprobablydecreasedreadability,
since,whenreadingthecode,onehastosearchforthetypeoffootoactuallyknowthetypeofbar.

Introductiontostrings
Fundamentaltypesrepresentthemostbasictypeshandledbythemachineswherethecodemayrun.Butoneofthe
majorstrengthsoftheC++languageisitsrichsetofcompoundtypes,ofwhichthefundamentaltypesaremerebuilding
blocks.

Anexampleofcompoundtypeisthestringclass.Variablesofthistypeareabletostoresequencesofcharacters,suchas
wordsorsentences.Averyusefulfeature!

Afirstdifferencewithfundamentaldatatypesisthatinordertodeclareanduseobjects(variables)ofthistype,the
programneedstoincludetheheaderwherethetypeisdefinedwithinthestandardlibrary(header<string>):

1 //myfirststring Thisisastring
2 #include<iostream> Edit
3 #include<string>
4 usingnamespacestd;
5
6 intmain()
7 {
8 stringmystring;
9 mystring="Thisisastring";
10 cout<<mystring;
11 return0;
12 }

Asyoucanseeinthepreviousexample,stringscanbeinitializedwithanyvalidstringliteral,justlikenumericaltype
variablescanbeinitializedtoanyvalidnumericalliteral.Aswithfundamentaltypes,allinitializationformatsarevalidwith
strings:

1 stringmystring="Thisisastring";
2 stringmystring("Thisisastring");
3 stringmystring{"Thisisastring"};

Stringscanalsoperformalltheotherbasicoperationsthatfundamentaldatatypescan,likebeingdeclaredwithoutan
initialvalueandchangeitsvalueduringexecution:

1 //myfirststring Thisistheinitialstringcontent
2 #include<iostream> Thisisadifferentstringcontent Edit
3 #include<string>
4 usingnamespacestd;
5
6 intmain()
7 {
8 stringmystring;
9 mystring="Thisistheinitialstringcontent";
10 cout<<mystring<<endl;
11 mystring="Thisisadifferentstringcontent";
12 cout<<mystring<<endl;
13 return0;
14 }

Note:insertingtheendlmanipulatorendstheline(printinganewlinecharacterandflushingthestream).

Thestringclassisacompoundtype.Asyoucanseeintheexampleabove,compoundtypesareusedinthesamewayas
fundamentaltypes:thesamesyntaxisusedtodeclarevariablesandtoinitializethem.

FormoredetailsonstandardC++strings,seethestringclassreference.

Previous: Next:
Structureofaprogram Constants
Index

Homepage|Privacypolicy
cplusplus.com,20002015Allrightsreservedv3.1
Spottedanerror?contactus

http://www.cplusplus.com/doc/tutorial/variables/ 4/4

Potrebbero piacerti anche