Variables & Constants in C++ - Types of Variables
Variables & Constants in C++ - Types of Variables
Variables&ConstantsinC++|Typesofvariables
category:
Programming Fundamentals
Table of Contents
1. Introduction
2. Types of Variables
Introduction
Somelanguageshavethemechanismtodeclareavariablewhenitisneededwithoutpre
pending by the data type. But C++ has no such mechanism. A variable must be
3. Declaration of Variable
declared before it is used. It is a must because the compiler wants to be aware of it.
1. ItmuststartwithanEnglishalphabetcharacters,bothlowercaseanduppercase,including
underscore(notahyphen).Itmaynotstartwithadigit.Therestisoptional.Itcaneither
bealetteroradigit(09).
2. C++keywordslikemaion,case,class,if,else,do,while,for,tyedef,etccannotbeusedas
avariablenames.
3. Itmustbeuniquewithinthescope.
There are no restrictions on the length. Legal C++ variable names are hello_world, number but not 1number. C++ is a case
sensitivelanguage.Thevariablenames,HELLO,hello,Hello,HellOaretreateddifferent.
Theunderscore_enhancesthereadabilityoflongvariablename.Thesecondandtheimportantthing,whichhasbeenmentioned,
istheuppercaseandlowercaselettersforvariablenames.Itisatthediscretionofprogrammertouseeitherone.Someprogrammers
http://www.bytenotes.com/content/variablesconstantsc
1/6
11/28/2016
Variables&ConstantsinC++|Typesofvariables
prefertouseacamelnotationlikemy_Age,emp_Salary.Whicheverapproachisused,itmustbeconsistentthroughouttheprogram.
Thenamegiventovariablesiscalledidentifiers.Itcanbedeclaredatthestartofanyblockofcode,butmostlyusedatthestartofthe
function.
TypesofVariables
Basicallytherearetwotypesofvariables,namely
LocalVariable
GlobalVariable
LocalVariable
Thelocalvariableiscreatedwhenthefunctionsgetscontrolandisdestroyedwhenthecontroltransfersbacktothecaller.
GlobalVariable
WhereastheGlobalVariableisknownandaccessiblethroughoutprogram.GlobalVariablesaredeclaredatthetopofthemodule.
DeclarationofVariable
ThedeclarationofavariableissimpleinC++language.Itbeginswiththedatatype, followed by at least a space, followed by the
nameofavariablewithasemicolon.Spaceisoptionalbeforethesemicolon.
ForExample
intmy_Age
intmy_Salary
int_employee
Ifdifferentvariablesareusingthesamedatatypeonthesamelinearealsoallowd,butcaremustbetakentoseparatetwowitha
commaexceptthelastonethatwouldendwithasemicolon.
ForExample
intmy_Age,my_Salary,_employee
UnlikeC,declarationinC++arestatements,usingthisdefinition,variablesmaybedeclaredanywherewithintheprogram.
Anylegalvariablenamecanbeused,ithelpstogiveasensiblenamethatgiveyoufruitfulmeaningofwhattheyarebeingusedfor.
Supposeyouaregivenashortprogramtoaddtwonumbersanddisplaytheaccumulativevalue.Forthis,youshouldusenum1and
num2,fortwonumbersandathirdvariablenamesumfortheresult.Alwaysuseappropriatenames,whichcanpreventyoufromextra
comments.Remember,C++programmerstendtoprefershortvariablenames.
Variableattributes
Avariableinaprogramminglanguagerepresentsastoragelocation.InC++,eachvariablehassixattributes,name,address,
type,value,scopeandthestorageclass.Thevariablenameisthelabeltoidentifyavariableinthesourceprogram.Theaddressofa
variableisthelocationinthecomputermemoryoccupiedbythatvariable.Incaseofassignment,avariablenameisrequiredonthe
http://www.bytenotes.com/content/variablesconstantsc
2/6
11/28/2016
Variables&ConstantsinC++|Typesofvariables
leftsideofanassignmentstatement.Thetypeofavariablereferstothesizethatistheamountofstorageoccupiedbythatvariable.
Tomakeissimpler,itisthedatatypeassociatedwiththatvariable.
Thescopeofthevariabledependswhereitisdeclaredthatislocalorglobal.Insomecases,avariableexistforshorttimethatis
destroyedautomaticallyduringtheexecutionofaprogrambutsometimesexistsintheentireprogram.Avariabledeclaredwiththe
storageclassdependswhetheritisboundatcompiletimeorexecutiontimeandtheyarealsoknownasstaticbindinganddynamic
bindingrespectively.
ConstantsinC++
Weknowthatbeforetheexecution,avariablehasnameandtypeatexecutiontime,ithasalocationandvalue.AconstantinC++
meansanunchangingvalueandeachconstanthasatypebutdoesnothavelocationexceptthestringconstant.
IntegerConstants
Integerconstants consist of one or more digits such as 0,1,2,3,4 or 115. Floating point constants contain a decimal point such as
4.15,10.05.Itcanalsobewritteninscientificnotationsuchas1E35means1*10^35or1E35means1*10^35.
CharacterConstants
Characterconstantsspecifythenumericvalueofthatparticularcharactersuchasaisthevalueofa.Somespecialconstantsarein
thefollowingtable.
SpecialCharacterConstants(EscapeSequence)
Constant Description
Constant Description
\a
Alarm
\\
Backslashitself
\b
Backspace
\'
SingleQuoteitself
\f
FormFeed
\''
doubleQuotesitself
\n
LineFeed
\?
questionMark
\r
CarriageReturn
\o
Nullterminationcharacter
\t
HorizontalTab
\0
OctalCode
\v
VerticalTab
\xh
HexadecimalCode
StringConstants
Stringconstantsconsistofcharactersenclosedindoublequotessuchas
Hello,World
The string is stored in the memory and the numeric value of that constant is the address of this memory. The string constant is
suffixedby\0,(thenullcharacter)bythecompiler.
BothCandC++useescapesequenceinthesamemannersuchas\ncharactertoproduceanewline.Allescapesequencesare
preceded by a backslash, which indicates a special sequence to the compiler. The compiler as a single character views each and
everyescapesequence.Itseemsandmayhavebeenexpectedthatanescapesequenceoccupies2byteswhichiswrong,itoccupies
onlyonebyte.
http://www.bytenotes.com/content/variablesconstantsc
3/6
11/28/2016
Variables&ConstantsinC++|Typesofvariables
Tags:
C++ Lecture Notes
SponsoredLinks
VisitingSingaporeOnABudget?HereAre34MichelinapprovedPlacesToEat
YoursSingapore
HowtoKillJointPainatHomeFast
ArthroPro
AreyoureadytoconquerAncientGreece?Already35millionplayers!
GrepolisOnlineFreeGame
Areyouastrategicthinker?Testyourskillswithmillionsofaddictedplayers!
SpartaFreeOnlineGame
WeightLossForTheLazy!UpTo20KgIn4Weeks!
Heart.org
'DogWhisperer'FacesCrueltyProbe
ReutersTV
0Comments
Recommend
ByteNotes
Share
Login
SortbyBest
Startthediscussion
Bethefirsttocomment.
Subscribe d AddDisqustoyoursiteAddDisqusAdd
http://www.bytenotes.com/content/variablesconstantsc
Privacy
4/6
11/28/2016
Variables&ConstantsinC++|Typesofvariables
byte-notes
google.com/+Byte-notes
Follow
+1
+ 277
CustomSearch
SEARCH
http://www.bytenotes.com/content/variablesconstantsc
5/6
11/28/2016
Variables&ConstantsinC++|Typesofvariables
Poll
Do you like the new design? How about the Tech blog Section
Yes
71%
No
13%
Needs some improvement (Tell us in comments plz)
16%
Total votes: 1435
Older polls
User login
Username *
Password *
http://www.bytenotes.com/content/variablesconstantsc
6/6