top button
Flag Notify
    Connect to us
      Site Registration

Site Registration

Why we need volatile variables in C

+7 votes
690 views

Where we need to use volatile variable? If possible please provide some real time example ?

posted Oct 29, 2013 by Mona Sharma

Share this question
Facebook Share Button Twitter Share Button LinkedIn Share Button

2 Answers

+5 votes

Keyword volatile says that the code related to the variable in question should not be optimized i.e. the code is written on purpose and does not need optimization.

Volatile tells the compiler not to optimize anything that has to do with the volatile variable. There is only one reason to use it: When you interface with hardware.

An example of declaring a simple volatile int type variable would be:

Volatile int x;
Int volatile x;
If you had a pointer variable where the memory pointed to was volatile you could indicate that using:

Volatile int * x;
Int volatile * x;
On the other hand, if you have a pointer variable where the address itself was volatile but the memory pointed to was not then we have:

Int * volatile x;
Last but certainly not least if there was a pointer variable where both the pointer address and the memory pointed to was both volatile then you could do:

Volatile int * volatile x;
Int volatile * volatile x;

answer Oct 30, 2013 by Giri Prasad
–2 votes

Yes, this is to avoid optimization and generally will be used in multi threading.

answer Oct 30, 2013 by sivanraj
Similar Questions
+1 vote

Also can we declare a variable as "constant volatile" ? if yes then what may be the possible reason to do so?

+6 votes

Let me put this in other way , const qualifier will not allow to change you the value so what is the need of going with const volatile. Do we really need it in our day to day programming

...