7

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.

SenthilKumar
  • 87
  • 1
  • 3
  • What kind of answer are you looking for? What do you mean by "where does it get stored in memory?" Are you looking to get its address? Are you trying to understand what pool of memory such variables come from in accord with the standard's definitions for such pools? – Nicol Bolas Jul 27 '13 at 18:10
  • 1
    @NicolBolas: I guess that part of the question is 'does qualifying a variable with `volatile` alter the memory location where the compiler places the variable', to which the answer is 'no'. – Jonathan Leffler Jul 27 '13 at 18:20
  • 1
    I cannot see how this is a duplicate of the other. The other is about "what is `volatile`", this one is "which result does it have concerning memory addresses". – glglgl Jul 27 '13 at 20:17
  • 1
    @JonathanLeffler: In my first example,i understand that global initialized variable(without volatile) gets stored in "Initialized data segment" and my 2nd example,since it is local variable(without volatile) it gets stored in stack.so when i add volatile keyword means does the variable storing place get changed?...Please clarify my doubt – SenthilKumar Jul 29 '13 at 05:25

2 Answers2

14

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.

DaoWen
  • 32,589
  • 6
  • 74
  • 101
  • sometimes it also helps to prevent some downsides of your compiler optimization-process like the elision of the `var` from the entire program. Basically the compiler keeps the `var` into account even if it's not used in entire program and so it doesn't delete it. – user2485710 Jul 27 '13 at 17:50
11

Adding a volatile qualifier to a variable declaration does not change its storage class.

In your first example, the variable has static storage and in the second example it has automatic storage; this is the case even if you remove the volatile qualifier.

ouah
  • 142,963
  • 15
  • 272
  • 331
  • Hi All,In my first example,i understand that global initialized variable(without volatile) gets stored in "Initialized data segment" and my 2nd example,since it is local variable(without volatile) it gets stored in stack.so when i add volatile keyword means does the variable place get changed? – SenthilKumar Jul 28 '13 at 04:16