Search code examples
cc99volatile

After casting a volatile variable in c, is the variable still volatile?


Let's say that I have a static global variable a, that is cast to an int in a function call during init(). After init(), is a still volatile when used in the function my_function_2?

static volatile int a;

init(void)
{
  my_function_1((int)a);
}

my_function_2(void)
{
/* After init(), is a still volatile? */
}

Does a need to be re-qualified as volatile in my_function_2()? I'm using c99.


Solution

  • It's undefined behavior to refer to the value through a non-qualified type. If you "cast away" volatile you aren't allowed to access that memory location through a non-volatile qualified type.

    C17 6.7.3/6:

    If an attempt is made to refer to an object defined with a volatile-qualified type through use of an lvalue with non-volatile-qualified type, the behavior is undefined

    You can however still do a copy of it:

    static volatile int a;
    int b = a;      // ok, lvalue conversion, drops qualifiers during copy
    *(int*)&a = ... // undefined behavior