volatile 用法
时间:2023-02-04 06:33:42 下载该word文档
>>>>>>>>嵌入式编程中经常用到volatile这个关键字,在网上查了下他的用法找到了下面这3>>>>>篇文章比较好的:>>>>>>>>>一:告诉>>>>compiler不能做任何优化>>>>>>>>比如要往某一地址送两指令:>>>>>>>>int*ip=...;//设备地址*ip=1;//第一个指令*ip=2;//第二个指令以上程序compiler可能做优化而成:int*ip=...;*ip=2;结果第一个指令丢失。如果用volatile,compiler就不允许做任何的优化,从而保证程序的原意:volatileint*ip=...;*ip=1;*ip=2;即使你要compiler做优化,它也不会把两次付值语句间化为一。它只能做其它的优化。这对devicedriver程序员很有用。二:表示用volatile定义的变量会在程序外被改变,每次都必须从内存中读取,而不能把他放在cache或寄存器中重复使用。如volatilechara;a=0;while(!a{//dosomethings;}doother(;如果没有volatiledoother(不会被执行还找到一篇比较详细的比较CONST和Volatile的文章8.4.ConstandvolatileThesearenewinStandardC,althoughtheideaofconsthasbeenborrowedfromC++.Letusgetonethingstraight:theconceptsofconstandvolatilearecompletelyindependent.Acommonmisconceptionistoimaginethatsomehowconstistheoppositeofvolatileandviceversa.Theyareunrelatedandyoushouldrememberthefact.Sinceconstdeclarationsarethesimpler,we'lllookatthemfirst,butonlyafterwehaveseenwherebothofthesetypequalifiersmaybeused.Thecompletelistofrelevantkeywordsis
>>>>>>>>charlongfloatvolatileshortsigneddoublevoid>>>>intunsignedconstInthatlist,constandvolatilearetypequalifiers,therestaretypespecifiers.>>>>Variouscombinationsoftypespecifiersarepermitted:>>>>char,signedchar,unsignedchar>>>>int,signedint,unsignedint>>>>shortint,signedshortint,unsignedshortint>>>>longint,signedlongint,unsignedlongint>>>>float>>>>doublelongdouble>>>>Afewpointsshouldbenoted.Alldeclarationstodowithanintwillbesignedanyway,sosignedisredundantinthatcontext.Ifanyothertypespecifierorqualifierispresent,thentheintpartmaybedropped,asthatisthedefault.Thekeywordsconstandvolatilecanbeappliedtoanydeclaration,includingthoseofstructures,unions,enumeratedtypesortypedefnames.Applyingthemtoadeclarationiscalledqualifyingthedeclaration—that'swhyconstandvolatilearecalledtypequalifiers,ratherthantypespecifiers.Hereareafew>>>>representativeexamples:>>>>volatilei;>>>>volatileintj;constlongq;>>>>constvolatileunsignedlongintrt_clk;struct{>>>