Continue to Site

Welcome to EDAboard.com

Welcome to our site! EDAboard.com is an international Electronics Discussion Forum focused on EDA software, circuits, schematics, books, theory, papers, asic, pld, 8051, DSP, Network, RF, Analog Design, PCB, Service Manuals... and a whole lot more! To participate you need to register. Registration is free. Click here to register now.

[General] Declaration of volatile variable (vs) global variable difference?

Status
Not open for further replies.

vedadribabu

Newbie level 5
Joined
Jan 13, 2011
Messages
8
Helped
0
Reputation
0
Reaction score
0
Trophy points
1,281
Activity points
1,322
Please clarify my doubt??

what is the difference?

1 .int a=1;
int a=2;

2.volatile int a=1;
volatile int a=2;

since volatile means variable can be changed at any time if we don't declare volatile also a is becoming 2 then what is reason if we decalre volatile?
 

you have to use volatile if your variable is used in interrupt routines
 

i am not considering interrupt case then what will happen? in this case
 

I dont understand, what is your point?

if you wrote this:

int a = 2;
int a = 3;

a good compilator gives you a warning or an error, because you are trying to declare two variables with the same name. When you declare variable without "volatile" the variable is common variable and you could use it everywhere in program except interrupt routines.
 

volatile tells the compiler that the variable may be changed by a machanism outside the programs flow of control.

So for example if I had a variable which was located by the linker in a memory location that was really a hardware status register then the hardware can change the value of that variable at any time.

if I declare the variable to be volatile and write :

volatile int status;
.
.
.
while (status & 0xE0) {};

the code will spin until the relevant bit is set (this is a very common thing to do when waiting for hardware to become ready in embedded systems).

Without the volatile, the compiler will optimise the loop possibly to either
while (1) {}; or even while (0){};
Which is not the same thing at all!

You can think of a volatile decaration as "Do not optimise accesses to this", the semantics are actually somewhat more subtle, but this gets the basic idea across.

HTH.

Regards, Dan.
 

Status
Not open for further replies.

Similar threads

Part and Inventory Search

Welcome to EDABoard.com

Sponsor

Back
Top