Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Where are volatile variables stored? [duplicate]

Tags:

c++

c

Can I know where the volatile variable is getting stored in the memory?

  1. If i declare globally means where does it get stored in the memory?

    volatile int a =10;
    int main()
    {
        printf("Global A value=%d",a);
        return 0;
    }
    
  2. If i declare locally inside the function means where does it get stored in the memory?

    int main()
    {
        volatile int a =10;
        printf("Local A value=%d",a);
        return 0;
    }
    

Does it get stored in Stack / RAM / Data segment ?

Please clarify my doubts.

like image 324
SenthilKumar Avatar asked Jul 27 '13 17:07

SenthilKumar


People also ask

Where is volatile variable stored?

There's no reason for a volatile variable to be stored in any "special" section of memory. It is normally stored together with any other variables, including non-volatile ones. If some compiler decides to store volatile variables in some special section of memory - there's nothing to prevent it from doing so.

Where are volatile variables stored in Java?

Volatile fields are instance or class (static) variables and are stored in the heap.

Are volatile variables cached?

Variables declared as volatile are not cached in registers between operations, so that if something writes to it outside the current thread of execution, the next time the current thread of execution needs it it will be read from the memory again each time it is used.

Where are const volatile variables stored in C?

As per the memory layout of C program, constant variables are stored in the; Initialised data segment of the RAM. Since RAM is mostly volatile, then the constants are stored in flash memory and may or may not be copied to RAM during initialisation.


1 Answers

volatile just tells the compiler it can't cache the value of the variable in a register—it doesn't change where it gets allocated.

like image 145
DaoWen Avatar answered Sep 23 '22 06:09

DaoWen