Using static and volatile

Go To Last Post
2 posts / 0 new
Author
Message
#1
  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

I have some questions about static and volatile keywords.

I understand static is normally used inside functions to keep the value in memory and volatile is used if theres some interrupt that would change the value outside the function.

So what I don't undestand is what does the static keyword do in the following,

static volatile unsigned char test;

void somefunction(void)
{
     test++;
}

If test is declared as attribute, it already keeps the value in memory so what's the point?

And the second question,

void somefunction(void)
{
    volatile unsigned char test;
    
    ...
    test++;
    ...
}

In which case does the test variable have to be volatile?

  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

electroz wrote:
I have some questions about static and volatile keywords.

These are standard 'C' keywords - nothing specifically to do with GCC or the AVR - so you should start with a good 'C' textbook!
K&R would be an ideal reference:
http://www.amazon.co.uk/exec/obi...

Quote:
I understand static is normally used inside functions to keep the value in memory

That is one use of static; the other is outside functions, where it restricts the identifier's "scope" to just the current compilation unit.
(strictly, it forces internal linkage)

Quote:
volatile is used if theres some interrupt that would change the value outside the function.

Again, that's just one application of volatile.
volatile advises the compiler that the object may be subject to change by some means not visible to it and, therefore, that it must not apply any optimisation that assumes otherwise.
Other common uses of volatile would be in multi-tasking systems, in shared memory, and in memory-mapped IO.
Volatile may also be needed to prevent a compiler from optimising-out software delay loops.

Hopefully, that should explain your questions?

Top Tips:

  1. How to properly post source code - see: https://www.avrfreaks.net/comment... - also how to properly include images/pictures
  2. "Garbage" characters on a serial terminal are (almost?) invariably due to wrong baud rate - see: https://learn.sparkfun.com/tutorials/serial-communication
  3. Wrong baud rate is usually due to not running at the speed you thought; check by blinking a LED to see if you get the speed you expected
  4. Difference between a crystal, and a crystal oscillatorhttps://www.avrfreaks.net/comment...
  5. When your question is resolved, mark the solution: https://www.avrfreaks.net/comment...
  6. Beginner's "Getting Started" tips: https://www.avrfreaks.net/comment...