U. Windl
U. Windl

Reputation: 4325

temporary volatile using casts

Some C library function omit warnings via the compiler when volatile values are passed to them; for example memcpy(). Now I wondered whether I could use some volatile casts to enforce immediate evaluation. Consider:

int b; /* ... */
(volatile int) b = 1;
b = (volatile int) 1;

Now does the second line cause immediate assignment to b, and does the third line do the same? Or can't a constant like 1 be made "more volatile" (meaning it won't have any effect)?

Upvotes: 0

Views: 50

Answers (1)

Eric Postpischil
Eric Postpischil

Reputation: 222753

Qualifiers (const, restrict, volatile, and _Atomic) never apply to values. They only apply to objects, because they tell the compiler something about how to handle the memory of an object.

So (volatile int) b and (volatile int) 1 have no effect different from (int) b and (int) 1.

You can access a non-volatile object with a volatile lvalue, as with * (volatile int *) &x = value;. Then the C implementation must access the object (read or write it) strictly according to the semantics of C’s abstract machine. It may be reordered with other non-volatile expressions generally but not with observable behaviors: accessing volatile objects, interactive I/O, and writing to files.

Upvotes: 1

Related Questions