Where all to use volatile keyword in C

Viewed 2035

I know volatile keyword prevents compiler from optimizing a variable and read it from memory whenever it is read. Apart from memory mapped registers, what are all the situations where we need to use volatile? Given a conforming compiler, do I have to declare test_var as volatile in both scenarios?

1.

In file1.c

int test_var=100;


void func1()
{
    test_var++;
}

In file2.c

extern int test_var;

void func2()
{
    if(test_var==100)
    {
      ....
    }
}

2.

In file1.c

int test_var=100;

void func1()
{

}

In file2.c

extern int test_var;

void func2()
{
    if(test_var==100)
    {
      ....
    }
}
5 Answers

Apart from memory mapped registers, what are all the situations where we need to use volatile?

If

  1. execution is purely sequential (no threads and no signals delivered asynchronously);
  2. you don't use longjmp;
  3. you don't need to be able to debug a program compiled with optimizations;
  4. you don't use constructs with vaguely specified semantics like floating point operations;
  5. you don't do useless computations (computations where the result is ignored) as in a benchmark loop;
  6. you don't do timings of any pure computations, that is anything that isn't I/O based (I/O based such as timings of accesses of network requests, external database accesses)

then you probably have no need for volatile.

Related