Search code examples
cpointersvolatile

Is the "volatile" property of pointers inherited?


Suppose I have the following code:

my_struct_member_type *foo() {
    volatile my_struct *s = (my_struct *)SOME_ADDRESS;
    return &(s->struct_member);
}

Is the pointer returned by foo also volatile?

EDIT: A followup: is the pointer &(s->struct_member) volatile inside of foo?


Solution

  • Yes.

    For volatile my_struct *s says that the object you see through it is volatile and all members that you access through this pointer inherit the volatile qualification.

    Having the address of a pointer to volatile returned if the return type doesn't say so is a constraint violation and your compiler must have given you a diagnostic for that.

    Edit: There also seems to be confusion to where the volatile keyword applies. In your example it applies to the object pointed to, not to the pointer itself. As a rule of thumb always write the qualifiers (const or volatile) as far to the right as possible without a type change. Your example then would read:

    my_struct volatile*s = (my_struct *)SOME_ADDRESS;
    

    which is entirely different from

    my_struct *volatile s = (my_struct *)SOME_ADDRESS;
    

    where the pointer itself is volatile but not the object behind it.

    Edit 2: Since you ask for my sources, the actual C standard, C11, 6.8.6.4 it says about the return statement:

    If the expression has a type different from the return type of the function in which it appears, the value is converted as if by assignment to an object having the return type of the function

    So 6.15.16.1 for the assignment operator what is expected from the conversion:

    the left operand has atomic, qualified, or unqualified pointer type, and (considering the type the left operand would have after lvalue conversion) both operands are pointers to qualified or unqualified versions of compatible types, and the type pointed to by the left has all the qualifiers of the type pointed to by the right;

    Here the pointed type on the right has the volatile qualifier in addtion to the one on the left.