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.

Volatile Variable in C?

Status
Not open for further replies.

A.Rashad

Member level 4
Joined
Jul 27, 2011
Messages
69
Helped
6
Reputation
10
Reaction score
5
Trophy points
1,288
Location
Pune
Activity points
1,792
What is Volatile Variable in C?
What is the role of Volatile variable in Embedded Application Programming?
Please Suggest Some Example code..
 

You can find many articles about this, for example

**broken link removed**
 

In case you are still struggling with it, here is a summary. Declare the variable as volatile if that variable can change its value outside of your C code. If you are certain that the variable is control entirely by the C code only and no hardware register or interrupt can modify it, then you dont need this "volatile" declaration.
 
what is a variable is shared by different modules of my code. In that case also do i need to declare that variable with volatile.

thanks
 

one example of the use in embedded application s is in interrupt service routines, e.g. usinga timer on a PIC24
Code:
volatile long unsigned int mSecCounter=0; 	// counts millisecond interrupts

/* interrupt service routine for Timer1 ISR*/
void __attribute__((__interrupt__, __shadow__)) _T1Interrupt(void)
{
int i;
/* Interrupt Service Routine code goes here */
IFS0bits.T1IF = 0; 							//Reset Timer1 interrupt flag	
mSecCounter++;													
}
a modern compiler will optimize removing code that does not appear to do anything
volatile tells the compiler not to optimize references to variable mSecCounter, e.g.
Code:
mSecCounter=0;
while(mSecCounter<1000) 
    ...;       // code executed for 1 second

- - - Updated - - -

what is a variable is shared by different modules of my code. In that case also do i need to declare that variable with volatile.

thanks
no, you define in one module and declare it extern in other modules that use it
https://www.learncpp.com/cpp-tutorial/42-global-variables/
 

Status
Not open for further replies.

Similar threads

Part and Inventory Search

Welcome to EDABoard.com

Sponsor

Back
Top