Nios® V/II Embedded Design Suite (EDS)
Support for Embedded Development Tools, Processors (SoCs and Nios® V/II processor), Embedded Development Suites (EDSs), Boot and Configuration, Operating Systems, C and C++
12747 Discussions

why use the "volatile" keyword

Altera_Forum
Honored Contributor II
1,153 Views

Hey guys, I'm working on some ISR sofware development, and I am wondering why the software developer's hand book declares variables as "volatile int*" and "volatile int" rather then just "int*" and "int". The manual says that "the volatile keyword only prevents the compiler from optomizing out accesses using the pointer". Does this mean if the volatile keyword isn't used the compiler will ignore statements involving referencing and dereferencing pointers? Thanks for the help! 

 

-Jon
0 Kudos
2 Replies
Altera_Forum
Honored Contributor II
442 Views

It's a bit hard to say why without referring to a specific example, however volatile is a standard C keyword and you should probaby refer to "The C Programming Language" by Kernighan and Ritchie. 

 

However volatile is used when you want to force the compile to actually load a variable from memory. 

 

For example if I have some code 

 

int a = *0x80000; //Load a from memory 

 

/* 

Do stuff 

*/ 

 

b = *0x80000; 

 

I the Do stuff code did not change the memory location 0x80000 the compiler may try to optimise and say well I knew what the contents were when I read a so I'll use the value I read before. 

 

This tends to be a problem when you are reading from something that can change such as; 

a piece of hardware 

or a piece of memory written to by some hardware or another piece of software (eg. foreground code and an ISR)
0 Kudos
Altera_Forum
Honored Contributor II
442 Views

ahh, makes sense. Thanks for the info rugbybloke. 

 

-jon
0 Kudos
Reply