395,969 Members | 4,480 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 395,969 IT Pros & Developers. It's quick & easy.

volatile variable in writing driver

praveeng
P: 1
what is the exact use of volatile variables in writing device drivers
Dec 11 '06 #1
Share this Question
Share on Google+
2 Replies


rengaraj
100+
P: 168
Normal variables { without the 'volatile' type specifier } can be stored in the cache to make the CPU access faster. There might be some situations where you don't want to cache a particular variable and you want to read the variable always from the specified location instead from cache. You declare those kind of variables as volatile.
Jan 31 '07 #2

Motoma
Expert 2.5K+
P: 3,235
what is the exact use of volatile variables in writing device drivers
Wecome to The Scripts.
The volatile keyword specifies that that variable may be changed from the outside. The biggest reason for this is to prevent an optimizing compiler from incorrectly removing checks.

Here is a nice excerpt from Wikipedia:

Expand|Select|Wrap|Line Numbers
  1. void foo(void)
  2. {
  3.     int *addr;
  4.     addr = 100;
  5.  
  6.     *addr = 0;
  7.  
  8.     while (*addr != 255)
  9.         ;
  10. }
  11.  
In this example, the code sets the value stored at location 100 in the computer system to 0. It then starts to poll the address until it changes to 255.

An optimizing compiler will assume that no other code will change the value stored in location 100 and so it will remain equal to 0. The compiler will then replace the while loop with something similar to this:

Expand|Select|Wrap|Line Numbers
  1. void foo(void)
  2. {
  3.     int *addr;
  4.     addr = 100;
  5.  
  6.     *addr = 0;
  7.  
  8.     while (TRUE)
  9.         ;                      /* do nothing, just loop */
  10. }
  11.  
and the program will loop forever.
Jan 31 '07 #3

Post your reply

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