Static Volatile Help

This is a discussion on Static Volatile Help within the C Programming forums, part of the General Programming Boards category; Hi all, I was studying a code and came across a variable definition as : static volatile int x; can ...

  1. #1
    Registered User
    Join Date
    Feb 2008
    Posts
    146

    Static Volatile Help

    Hi all,

    I was studying a code and came across a variable definition as :

    static volatile int x;

    can anybody help me understand its behaviour during runtime?

    Thanks,
    Edesign

  2. #2
    Registered User
    Join Date
    Sep 2004
    Location
    California
    Posts
    3,246
    static refers to the scope of the variable. If the variable is global, it means that the scope is limited to the source file it was declared in. If the variable is local to a function, then it means the memory used to hold this variable is in the application's statically allocated memory. An example of how this effects your program could be seen with:
    Code:
    void foo(void)
    {
        static int x = 0;
        x++;
        printf("%d\n", x);
    }
    Every time foo() is called, the value of x is increased. Try this in a program and compare the difference of when x is declared as static vs x being declared normally.

    The volatile keyword is used to indicate that the compiler should not perform optimizations which cache the value of the variable. It forces the compiler to generate code which always goes to memory to read the value stored in the variable. This is useful if you know that the memory location that this variable is at may be modified outside the scope of your application. An example would be in embedded devices that use memory mapped registers.

  3. #3
    Registered User
    Join Date
    Feb 2008
    Posts
    146
    @bithub
    Thanks that was clear.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Seg Fault in Compare Function
    By tytelizgal in forum C Programming
    Replies: 1
    Last Post: 10-25-2008, 03:06 PM
  2. seg fault at vectornew
    By tytelizgal in forum C Programming
    Replies: 2
    Last Post: 10-25-2008, 01:22 PM
  3. LNK2001 ERROR!!! need help
    By lifeafterdeath in forum C++ Programming
    Replies: 7
    Last Post: 05-27-2008, 05:05 PM
  4. get keyboard and mouse events
    By ratte in forum Linux Programming
    Replies: 10
    Last Post: 11-17-2007, 04:42 PM
  5. Replies: 16
    Last Post: 10-29-2006, 04:04 AM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21