Beruflich Dokumente
Kultur Dokumente
signup
login
tour
help
StackOverflowisacommunityof4.7millionprogrammers,justlikeyou,helpingeachother.Jointhem,itonlytakesaminute:
stackoverflowcareers
Signup
WhyisvolatileneededinC?
Whyis
volatileneededinC?Whatisitusedfor?Whatwillitdo?
c declaration volatile
editedMay27at17:57
askedOct29'08at8:36
JonathanLeffler
383k
52
414
thomas
705
http://stackoverflow.com/questions/72552/cwhenhasthevolatilekeywordeverh
elpedyou
FrederikSlijkermanOct29'08at8:45
14Answers
Volatiletellsthecompilernottooptimizeanythingthathastodowiththevolatilevariable.
Thereisonlyonereasontouseit:Whenyouinterfacewithhardware.
Let'ssayyouhavealittlepieceofhardwarethatismappedintoRAMsomewhereandthathas
twoaddresses:acommandportandadataport:
typedefstruct
{
intcommand
intdata
intisbusy
}MyHardwareGadget
Nowyouwanttosendsomecommand:
voidSendCommand(MyHardwareGadget*gadget,intcommand,intdata)
{
//waitwhilethegadgetisbusy:
while(gadget>isbusy)
{
//donothinghere.
}
//setdatafirst:
gadget>data=data
//writingthecommandstartstheaction:
gadget>command=command
}
Lookseasy,butitcanfailbecausethecompilerisfreetochangetheorderinwhichdataand
commandsarewritten.Thiswouldcauseourlittlegadgettoissuecommandswiththeprevious
datavalue.Alsotakealookatthewaitwhilebusyloop.Thatonewillbeoptimizedout.The
compilerwilltrytobeclever,readthevalueofisbusyjustonceandthengointoaninfinite
loop.That'snotwhatyouwant.
Thewaytogetaroundthisistodeclarethepointergadgetasvolatile.Thiswaythecompileris
forcedtodowhatyouwrote.Itcan'tremovethememoryassignments,itcan'tcachevariables
inregistersanditcan'tchangetheorderofassignmentseither:
Thisisthecorrectversion:
voidSendCommand(volatileMyHardwareGadget*gadget,intcommand,intdata)
{
//waitwhilethegadgetisbusy:
while(gadget>isbusy)
{
//donothinghere.
}
//setdatafirst:
gadget>data=data
//writingthecommandstartstheaction:
gadget>command=command
}
http://stackoverflow.com/questions/246127/why-is-volatile-needed-in-c
1/6
11/12/2015
answeredOct29'08at8:45
VikasGoel
NilsPipenbrinck
162
49.2k
14
16
108
187
13 Personally,I'dprefertheintegersizetobeexplicitye.g.int8/int16/int32whentalkingtohardware.Nice
answerthough)tonyloOct29'08at8:53
5
yes,youshoulddeclarethingswithafixedregistersize,butheyit'sjustanexample.NilsPipenbrinck
Oct29'08at8:54
34 Volatileisalsoneededinthreadedcodewhenyouareplayingwithdatathatisn'tconcurrencyprotected.
Andyestherearevalidtimestobedoingthat,youcanforexamplewriteathreadsafecircularmessage
queuewithoutneedingexplicitconcurrencyprotection,butitwillneedvolatiles.tolomeaOct29'08at
9:57
5
ReadtheCspecificationharder.VolatileonlyhasdefinedbehavioronmemorymappeddeviceI/Oor
memorytouchedbyanasynchronousinterruptingfunction.Itsaysnothingaboutthreading,andacompiler
whichoptimizesawayaccesstomemorytouchedbymultiplethreadsisconformant.ephemientOct29
'08at14:36
Doyouhaveareferenceforthatclaim?EveryreferenceI'veseensaysvolatiletellsthecompilernotto
optimizememoryaccessesonwhatever.I'veneverseenarestrictiononwhetherthememoryisRAMor
IO.Furtheronmanyplatformsthecompilercan'tdistinguishbetweenRAMandmemorymappedIO.
tolomeaOct29'08at22:28
Anotherusefor
volatileissignalhandlers.Ifyouhavecodelikethis:
quit=0
while(!quit)
{
/*verysmallloopwhichiscompletelyvisibletothecompiler*/
}
Thecompilerisallowedtonoticetheloopbodydoesnottouchthe quitvariableandconvert
thelooptoa while(true)loop.Evenifthe quitvariableissetonthesignalhandlerfor
SIGINTand SIGTERMthecompilerhasnowaytoknowthat.
However,ifthe quitvariableisdeclared volatile,thecompilerisforcedtoloaditevery
time,becauseitcanbemodifiedelsewhere.Thisisexactlywhatyouwantinthissituation.
answeredOct29'08at10:52
CesarB
21.9k
45
64
whenyousay"thecompilerisforcedtoloaditeverytime,isitlikewhencompilerdecidetooptimizea
certainvariableandwedon'tdeclarethevariableasvolatile,atruntimethatcertainvariableisloadedto
CPUregistersnotinmemory?AmitSinghTomarMar17at16:34
volatiletellsthecompilerthatyourvariablemaybechangedbyothermeans,thanthecode
thatisaccessingit.e.g.,itmaybeaI/Omappedmemorylocation.Ifthisisnotspecifiedin
suchcases,somevariableaccessescanbeoptimised,e.g.,itscontentscanbeheldina
register,andthememorylocationnotreadbackinagain.
answeredOct29'08at8:41
ChrisJesterYoung
132k
26
251
331
volatileinCactuallycameintoexistenceforthepurposeofnotcacheingthevaluesofthe
variableautomatically.Itwilltellthemachinenottocachethevalueofthisvariable.Soitwill
takethevalueofthegiven volatilevariablefromthemainmemoryeverytimeitencounters
it.ThismechanismisusedbecauseatanytimethevaluecanbemodifiedbytheOSorany
interrupt.Sousing volatilewillhelpusaccessingthevalueafresheverytime.
editedOct29'08at8:46
answeredOct29'08at8:44
MatthewScharley
53.2k
36
138
ManojDoubts
188
2,848
12
30
40
simpleandbestexplanation.nikkFeb20at19:15
http://stackoverflow.com/questions/246127/why-is-volatile-needed-in-c
2/6
11/12/2015
SeethisarticlebyAndreiAlexandrescu,"volatileMultithreadedProgrammer'sBestFriend"
Thevolatilekeywordwasdevisedtopreventcompileroptimizationsthatmightrendercode
incorrectinthepresenceofcertainasynchronousevents.Forexample,ifyoudeclarea
primitivevariableasvolatile,thecompilerisnotpermittedtocacheitinaregistera
commonoptimizationthatwouldbedisastrousifthatvariableweresharedamongmultiple
threads.Sothegeneralruleis,ifyouhavevariablesofprimitivetypethatmustbeshared
amongmultiplethreads,declarethosevariablesvolatile.Butyoucanactuallydoalot
morewiththiskeyword:youcanuseittocatchcodethatisnotthreadsafe,andyoucando
soatcompiletime.Thisarticleshowshowitisdonethesolutioninvolvesasimplesmart
pointerthatalsomakesiteasytoserializecriticalsectionsofcode.
Thearticleappliestoboth
Cand C++.
Alsoseethearticle"C++andthePerilsofDoubleCheckedLocking"byScottMeyersand
AndreiAlexandrescu:
Sowhendealingwithsomememorylocations(e.g.memorymappedportsormemory
referencedbyISRs[InterruptServiceRoutines]),someoptimizationsmustbesuspended.
volatileexistsforspecifyingspecialtreatmentforsuchlocations,specifically:(1)thecontent
ofavolatilevariableis"unstable"(canchangebymeansunknowntothecompiler),(2)all
writestovolatiledataare"observable"sotheymustbeexecutedreligiously,and(3)all
operationsonvolatiledataareexecutedinthesequenceinwhichtheyappearinthesource
code.Thefirsttworulesensureproperreadingandwriting.Thelastoneallows
implementationofI/Oprotocolsthatmixinputandoutput.ThisisinformallywhatCand
C++'svolatileguarantees.
editedJul27'10at14:56
answeredJul22'10at12:33
RobertS.Barnes
20.8k
13
91
141
Doesthestandardspecifywhetherareadisconsidered'observablebehavior'ifthevalueisneverused?My
impressionisthatitshouldbe,butwhenIclaimeditwaselsewheresomeonechallengedmeforacitation.It
seemstomethatonanyplatformwhereareadofavolatilevariablecouldconceivablyhaveanyeffect,a
compilershouldberequiredgeneratecodethatperformseveryindicatedreadpreciselyoncewithoutthat
requirement,itwouldbedifficulttowritecodewhichgeneratedapredictablesequenceofreads.supercat
Oct13'10at22:50
@supercat:Accordingtothefirstarticle,"Ifyouusethevolatilemodifieronavariable,thecompilerwon't
cachethatvariableinregisterseachaccesswillhittheactualmemorylocationofthatvariable."Also,in
section6.7.3.6ofthec99standarditsays:"Anobjectthathasvolatilequalifiedtypemaybemodifiedin
waysunknowntotheimplementationorhaveotherunknownsideeffects."Itfurtherimpliesthatvolatile
variablesmaynotbecachedinregistersandthatallreadsandwritesmustbeexecutedinorderrelativeto
sequencepoints,thattheyareinfactobservable.RobertS.BarnesOct14'10at8:28
Thelatterarticleindeedstatesexplicitlythatreadsaresideeffects.Theformerindicatesthatreadscannot
beperformedoutofsequence,butdidnotseemtoprecludethepossibilityofthembeingelidedaltogether.
supercatOct14'10at20:31
Amarginaluseforvolatileisthefollowing.Sayyouwanttocomputethenumericalderivative
ofafunction f:
doubleder_f(doublex)
{
staticconstdoubleh=1e3
return(f(x+h)f(x))/h
}
butdependingonyourplatformandcompilerswitches,thesecondlineofthatfunctionmaybe
wipedoutbyaaggressivelyoptimizingcompiler.Soyouwriteinstead
http://stackoverflow.com/questions/246127/why-is-volatile-needed-in-c
3/6
11/12/2015
volatiledoublehh=x+h
hh=x
toforcethecompilertoreadthememorylocationcontaininghh,forfeitinganeventual
optimizationopportunity.
editedJun1'14at9:40
answeredJun30'10at11:34
AlexandreC.
35.4k
71
150
Mysimpleexplanationis:
Insomescenarios,basedonthelogicorcode,thecompilerwilldooptimisationofvariables
whichitthinksdonotchange.The volatilekeywordpreventsavariablebeingoptimised.
Forexample:
boolusb_interface_flag=0
while(usb_interface_flag==0)
{
//executelogicforthescenariowheretheUSBisn'tconnected
}
Fromtheabovecode,thecompilermaythink usb_interface_flagisdefinedas0,andthatin
thewhileloopitwillbezeroforever.Afteroptimisation,thecompilerwilltreatitas
while(true)allthetime,resultinginaninfiniteloop.
Toavoidthesekindsofscenarios,wedeclaretheflagasvolatile,wearetellingtocompiler
thatthisvaluemaybechangedbyanexternalinterfaceorothermoduleofprogram,i.e.,
pleasedon'toptimiseit.That'stheusecaseforvolatile.
editedApr20at13:23
answeredJan24at7:01
PROGRAM_IX
VenkatakrishnaKalepalli
161
121
14
I'llmentionanotherscenariowherevolatilesareimportant.
SupposeyoumemorymapafileforfasterI/Oandthatfilecanchangebehindthescenes(e.g.
thefileisnotonyourlocalharddrive,butisinsteadservedoverthenetworkbyanother
computer).
Ifyouaccessthememorymappedfile'sdatathroughpointerstononvolatileobjects(atthe
sourcecodelevel),thenthecodegeneratedbythecompilercanfetchthesamedatamultiple
timeswithoutyoubeingawareofit.
Ifthatdatahappenstochange,yourprogrammaybecomeusingtwoormoredifferent
versionsofthedataandgetintoaninconsistentstate.Thiscanleadnotonlytologically
incorrectbehavioroftheprogrambutalsotoexploitablesecurityholesinitifitprocesses
untrustedfilesorfilesfromuntrustedlocations.
Ifyoucareaboutsecurity,andyoushould,thisisanimportantscenariotoconsider.
answeredNov26'11at10:05
AlexeyFrunze
41.8k
33
75
Therearetwouses.Thesearespeciallyusedmoreofteninembeddeddevelopment.
http://stackoverflow.com/questions/246127/why-is-volatile-needed-in-c
4/6
11/12/2015
1. Compilerwillnotoptimisethefunctionsthatusesvariablesthataredefinedwithvolatile
keyword
2. VolatileisusedtoaccessexactmemorylocationsinRAM,ROM,etc...Thisisusedmore
oftentocontrolmemorymappeddevices,accessCPUregistersandlocatespecific
memorylocations.
Seeexampleswithassemblylisting.Re:UsageofC"volatile"KeywordinEmbedded
Development
answeredJul30'11at4:59
NeoCambell
51
Volatileisalsouseful,whenyouwanttoforcethecompilernottooptimizeaspecificcode
sequence(e.g.forwritingamicrobenchmark).
answeredOct29'08at8:46
DiomidisSpinellis
10.3k
26
52
volatilemeansthestorageislikelytochangeatanytimeandbechangedbutsomething
outsidethecontroloftheuserprogram.Thismeansthatifyoureferencethevariable,the
programshouldalwayscheckthephysicaladdress(ieamappedinputfifo),andnotuseitina
cachedway.
Alsoseethearticleathttp://clinuxpro.com/volatileinc
answeredJul9'11at3:14
Structurepadding
81
Avolatilecanbechangedfromoutsidethecompiledcode(forexample,aprogrammaymapa
volatilevariabletoamemorymappedregister.)Thecompilerwon'tapplycertainoptimizations
tocodethathandlesavolatilevariableforexample,itwon'tloaditintoaregisterwithout
writingittomemory.Thisisimportantwhendealingwithhardwareregisters.
answeredOct29'08at8:45
OriPessach
5,344
TheWikisayeverythingabout
28
48
volatile:
volatile(computerprogramming)
AndtheLinuxkernel'sdocalsomakeaexcellentnotationabout
volatile:
Whythe"volatile"typeclassshouldnotbeused
editedAug30at18:42
answeredSep5'12at14:54
MahendraGunawardena
coanor
368
997
20
10
25
itdoesnotallowscompilertoautomaticchangingvaluesofvariables.avolatilevariableisfor
dynamicuse.
answeredMay21'10at19:23
venu
11
http://stackoverflow.com/questions/246127/why-is-volatile-needed-in-c
5/6
11/12/2015
protectedbytchristSep5'12at18:36
Thankyouforyourinterestinthisquestion.Becauseithasattractedlowqualityanswers,postingananswernowrequires10reputationonthissite.
Wouldyouliketoansweroneoftheseunansweredquestionsinstead?
http://stackoverflow.com/questions/246127/why-is-volatile-needed-in-c
6/6