Vous êtes sur la page 1sur 6

11/28/2016

Variables&ConstantsinC++|Typesofvariables

Byte-Notes | Computer Science learning platform

Variables & Constants in C++


By Jawad Khan
20 / Jul / 2012

category:
Programming Fundamentals

Table of Contents

"A variable is a temporary container to store information, it is a named location in


computer memory where varying data like numbers and characters can be stored and
manipulatedduringtheexecutionoftheprogram".

1. Introduction
2. Types of Variables

Introduction

2.1. Local Variable

Somelanguageshavethemechanismtodeclareavariablewhenitisneededwithoutpre

2.2. Global Variable

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.

3.0.1. For Example

When declaring a variable, a few naming conventions must be taken in consideration.


Python - 10

3.0.2. For Example


4. Variable attributes
5. Constants in C++
5.1. Integer Constants
5.2. Character Constants
5.3. String Constants

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

Vous aimerez peut-être aussi