+ 2

C - Why can't I use auto, extern, static or register variables in a union?

Try this code with all four storage classes: #include <stdio.h> union Data{ int a; double b; auto int c; }; int main() { union Data data; printf("%lu",sizeof(data)); return 0; } They all give the same error. Why?

9th Feb 2020, 11:11 AM
Paolo De Nictolis
Paolo De Nictolis - avatar
2 Respostas
+ 7
In a union all variables are stored at the same address. If a has the storage class auto and b register they would be stored at different addresses but this is not allowed in a union.
9th Feb 2020, 11:51 AM
Aaron Eberhardt
Aaron Eberhardt - avatar
+ 6
Well, this one is interesting. These keywords mean different things in C than in C++. In C, they are all "storage-class specifiers". https://devdocs.io/c/language/storage_duration Why can't storage-class specifiers be used in unions (and structs), to declare their members? "For any struct or union declared with a storage-class specifier, the storage duration (but not linkage) applies to their members, recursively." The C language dictates that the storage duration of a member within an union cannot be defined separately from other members. What we can do is to define the storage duration of the union instance. E.g. static union Data data; auto union Data data2;
9th Feb 2020, 12:35 PM
Hatsy Rei
Hatsy Rei - avatar