0% found this document useful (0 votes)
163 views6 pages

Declaration - Why Is Volatile Needed in C - Stack Overflow

Volatile tells the compiler not to optimize code involving a volatile variable. It is used when interfacing with hardware to prevent the compiler from reordering reads and writes to memory-mapped hardware registers or optimizing away code that checks hardware status flags. Without volatile, the compiler is allowed to cache volatile variables in registers, reorder memory accesses, or remove apparently redundant code, which could cause problems when interacting with asynchronous external hardware.

Uploaded by

Ahmed Mousa
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
163 views6 pages

Declaration - Why Is Volatile Needed in C - Stack Overflow

Volatile tells the compiler not to optimize code involving a volatile variable. It is used when interfacing with hardware to prevent the compiler from reordering reads and writes to memory-mapped hardware registers or optimizing away code that checks hardware status flags. Without volatile, the compiler is allowed to cache volatile variables in registers, reorder memory accesses, or remove apparently redundant code, which could cause problems when interacting with asynchronous external hardware.

Uploaded by

Ahmed Mousa
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 6

11/12/2015

declaration - Why is volatile needed in C? - Stack Overflow

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

declaration - Why is volatile needed in C? - Stack Overflow


editedDec12'13at9:23

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

declaration - Why is volatile needed in C? - Stack Overflow

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
}

Theproblemisthat x+hxisgenerallynotequalto hduetoroundofferrors.Thinkaboutit:


whenyousubstractveryclosenumbers,youlosealotofsignificantdigitswhichcanruinthe
computationofthederivative(think1.000011).Apossibleworkaroundcouldbe
doubleder_f2(doublex)
{
staticconstdoubleh=1e3
doublehh=x+hx
return(f(x+hh)f(x))/hh
}

butdependingonyourplatformandcompilerswitches,thesecondlineofthatfunctionmaybe
wipedoutbyaaggressivelyoptimizingcompiler.Soyouwriteinstead
http://stackoverflow.com/questions/246127/why-is-volatile-needed-in-c

3/6

11/12/2015

declaration - Why is volatile needed in C? - Stack Overflow

volatiledoublehh=x+h
hh=x

toforcethecompilertoreadthememorylocationcontaininghh,forfeitinganeventual
optimizationopportunity.
editedJun1'14at9:40

answeredJun30'10at11:34
AlexandreC.
35.4k

71

150

Whatisadifferencebetweenusing hor hhinderivativeformula?When hhiscomputedthelast


formulausesitlikethefirstone,withnodifference.Maybeitshouldbe (f(x+h)f(x))/hh?
user128048Sep22'14at6:02
1 Thedifferencebetween hand hhisthat hhistruncatedtosomenegativepoweroftwobythe
operation x+hx.Inthiscase, x+hhand xdifferexactlyby hh.Youcanalsotakeyour
formula,itwillgivethesameresult,since x+hand x+hhareequal(itisthedenominatorwhichis
importanthere).AlexandreC.Sep22'14at18:16
1 Isn'tmorereadablewaytowritethiswouldbe x1=x+hd=(f(x1)f(x))/(x1x)?withoutusingthe
volatile.user128048Sep24'14at19:19

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

declaration - Why is volatile needed in C? - Stack Overflow

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

declaration - Why is volatile needed in C? - Stack Overflow

protectedbytchristSep5'12at18:36
Thankyouforyourinterestinthisquestion.Becauseithasattractedlowqualityanswers,postingananswernowrequires10reputationonthissite.
Wouldyouliketoansweroneoftheseunansweredquestionsinstead?

http://stackoverflow.com/questions/246127/why-is-volatile-needed-in-c

6/6

You might also like