2

I assume something like this cast is legal (where foo is a pointer to void) :

struct on_off {
                  unsigned light : 1;
                  unsigned toaster : 1;
                  int count;            /* 4 bytes */
                  unsigned ac : 4;
                  unsigned : 4;
                  unsigned clock : 1;
                  unsigned : 0;
                  unsigned flag : 1;
                 };

((on_off) foo).count = 3;

But I'm wondering if the struct is not defined whether something like this is legal :

((struct {
                  unsigned light : 1;
                  unsigned toaster : 1;
                  int count;            /* 4 bytes */
                  unsigned ac : 4;
                  unsigned : 4;
                  unsigned clock : 1;
                  unsigned : 0;
                  unsigned flag : 1;
         }) foo).count = 3;

... or something along these lines.

Thanks!

user207421
  • 305,947
  • 44
  • 307
  • 483
Anthony
  • 604
  • 6
  • 18
  • 1
    There are several problems with `((on_off) foo).count = 3;`. (1) `on_off` is undeclared; the type you declared is `struct on_off`. (2) You can't cast to a struct type. (3) A cast-expression is not an lvalue, so it can't be on the LHS of an assignment. I think what you mean is `((struct on_off*)foo)->count = 3;` – Keith Thompson Jul 23 '13 at 06:45

1 Answers1

3

Yes, C allows casting to anonymous structures. Here is a quick demo:

struct xxx {
    int a;
};
...
// Declare a "real"struct, and assign its field
struct xxx x;
x.a = 123;
// Cast a pointer of 'x' to void*
void *y = &x;
// Access a field of 'x' by casting to an anonymous struct
int b = ((struct {int a;}*)y)->a;
printf("%d\n", b); // Prints 123

Demo on ideone.

Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523