Anonymous structure declarations are legal in Ansi C?

I assume something like this 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 structure is structured, 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 like that.

Thanks!

+2
source share
1 answer

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; xa = 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 ideon .

+3
source

Source: https://habr.com/ru/post/1213162/


All Articles