By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
446,408 Members | 945 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 446,408 IT Pros & Developers. It's quick & easy.

volatile variable

P: 28
can any one tell me whats the use of volatile variable,i know by declaring variable as volatile makes compiler not to optimize while compilation,but whats the use of not optimizing.can any one tell me with giving example.
Jun 12 '06 #1
Share this Question
Share on Google+
1 Reply


Banfa
Expert Mod 5K+
P: 8,916
Easy if you work in embedded software (as I do) when you are accessing hardware external to the processor then you may wish to read or write to the same address more than once like so
Expand|Select|Wrap|Line Numbers
  1. #define CONFIG_REGISTER    ((ULONG *)0xC4000000)
  2. #define INPUT_REGISTER    ((ULONG *)0xC4000004)
  3.  
  4. *CONFIG_REGISTER = 0x80003000;
  5. *CONFIG_REGISTER = 0x40050000;
  6.  
  7. char data[10];
  8. int x;
  9.  
  10. for( x=0; x<10; x++ )
  11. {
  12.     data[x] = *INPUT_REGISTER;
  13. }
  14.  
As declared this wont work because the optomiser will optomise out the multiple consecutive reads or writes to the same location, the volitile specifier stops this by informaing the compiler that it can assume nothing about how that variable works so correctly written this is

Expand|Select|Wrap|Line Numbers
  1. #define CONFIG_REGISTER    ((volatile ULONG *)0xC4000000)
  2. #define INPUT_REGISTER    ((volatile ULONG *)0xC4000004)
  3.  
  4. *CONFIG_REGISTER = 0x80003000;
  5. *CONFIG_REGISTER = 0x40050000;
  6.  
  7. char data[10];
  8. int x;
  9.  
  10. for( x=0; x<10; x++ )
  11. {
  12.     data[x] = *INPUT_REGISTER;
  13. }
  14.  
Jun 13 '06 #2

Post your reply

Sign in to post your reply or Sign up for a free account.