volatile structures: Is that a bug?

Etienne Lorrain etienne_lorrain@yahoo.fr
Fri Sep 19 15:31:00 GMT 2008


 Hello,

On C structures, for attributes like "const", it is enough to consider
that each field inherit the attribute of the structure.
But for the volatile attribute, is it valid to treat each field as
volatile like GCC does it now?
I mean:
volatile struct { unsigned char a,b,c,d; } volstruct;
void fct (void) { volstruct.a ++; }
Is it valid to optimise to a byte read/increment/write, i.e. not
read and rewrite b, c and d?

I know that it has no consequences on ia32/64 kind of hardware where
most of the devices are in the I/O space, but for PPC it is usual
to have devices in I/O space - or for instance variables which can
only be accessed by 32 bits reads/writes (even if the field is itself
8 bits).
To force 32 bits access on a 8 bits field I/O, is it valid to do:
volatile struct { unsigned char field; unsigned char pad[3]; } io;
void fct (void) { io.field = 43; }

Also, the same question for unions, do the fields of the union
inherit the volatile attribute - or is the union itself volatile,
so that to force 32 bits access you can write:
volatile union { unsigned access32bits; unsigned char field; } io;
void fct (void) { io.field = 43; }

And what happens in C++, where you can write:
struct { volatile unsigned char field; unsigned char pad[3]; } io;
and:
volatile struct { unsigned char field; unsigned char pad[3]; } io;

 Sorry if that question has already been posted, I did not find
the official answer. I was thinking GCC behaved differently long time
ago. I do not like to write a lot of #define to cast everything to
a "volatile int *"...

 Thanks,
 Etienne.





More information about the Gcc mailing list