`volatile' on local variable used outside of function

Discussion in 'C Programming' started by nickptar, Dec 27, 2005.

  1. nickptar

    nickptar Guest

    Let's say I have a situation like this:

    /* begin example.c */
    static int* ptr;

    static void inner_fn(void)
    *ptr = 1;

    void outer_fn(void)
    int i = 0;
    ptr = &i;
    printf("%d\n", i);
    /* end example.c */

    in which a global pointer is set to point to a function-local variable
    and then written to in another function. Do I then have to declare `i'
    as `volatile' to get the expected behavior?
    nickptar, Dec 27, 2005
    1. Advertisements

  2. No.

    Effectively, you only need volatile for variables that might
    be changed by something outside the normal flow of control,
    such as by a signal handler.

    You do, though, need to #include <stdio.h> to get the expected behaviour.
    And you will need a main() somewhere along the line.
    Walter Roberson, Dec 27, 2005
    1. Advertisements

  3. nickptar

    Guillaume Guest

    Any decent compiler should detect that you're using a pointer to this
    local variable. I don't think you need to declare it "volatile".

    If I'm wrong, I'd like to see a reasonable explanation.
    Guillaume, Dec 27, 2005
  4. If the "expected behavior" is that calling inner_fn() sets i to 1, then
    there is absolutely no need to declare i as volatile. "volatile" is used
    for objects that could be modified by things outside your C code.

    Actually, declaring i as volatile int would be a huge mistake: If an
    object is volatile, then it is illegal to modify it through a
    non-volatile pointer, and it invokes undefined behavior. You would have
    to change the declaration of ptr to:

    static volatile int* ptr;
    Christian Bau, Dec 27, 2005
    1. Advertisements

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments (here). After that, you can post your question and our members will help you out.