what is specific use of volatile in c

I'm very confused about volatile variable I don't understand how it works as I know volatile variable used in interrupt service routine but I don't have idea why its useful in interrupt.

As much as i understand volatile variable can be change at anytime by outside the program flow

What is specif use of volatile variable in c ?

The volatile qualifier is used to ensure that the compiler doesn't optimise away accesses to the variable.

bool flag;
....

void someFunction ()
{
  flag = true;
  while (flag) {
     ... some code here that doesn't affect "flag", 
     ... the compiler could reasonably assume
     ... the loop will go on forever, so "flag" never
     ... actually needs to be fetched again
  }
}

imagine you have this loop:

uint8_t aVariable = 0; 
for (uint32_t i = 0; i < 10000000UL; i++) {
  aVariable += random(0, 10);
}

as aVariable easily fits in a register and will be accessed many times during the loop, the compiler will be tempted to just use a 8 bit register during the 10,000,000 iterations and store the result back into aVariable after the loop is ended as accessing memory is "slow".

Now imagine that an interruption arrives during that long for loop and you want to read aVariable --> it would be still 0 as no data would have been committed to memory yet.

Volatile addresses this issue. Every time the code tries to access a volatile variable, the compiler will generate code that goes read or write the SRAM and does not optimize the code by storing the data in a register for a while before committing the information into memory. This way if you get interrupted, what is really in memory (SRAM) is the latest and greatest information.

makes sense?

Using the volatile Keyword in Embedded C

JimEli:
Using the volatile Keyword in Embedded C

Shockingly bad sound quality