Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

union containing only one struct

Tags:

c

struct

unions

I have started today to program on a PIC16f88, and found that the header for its registers contains a union that only contains a struct:

extern volatile unsigned char ANSEL __at(0x09B);
typedef union {
    struct {
        unsigned ANS0       :1;
        unsigned ANS1       :1;
        unsigned ANS2       :1;
        unsigned ANS3       :1;
        unsigned ANS4       :1;
        unsigned ANS5       :1;
        unsigned ANS6       :1;
    };
} ANSELbits_t;
extern volatile ANSELbits_t ANSELbits __at(0x09B);

Does it provide any benefits to enclose the struct inside a union that only contains that struct?

Its access I guess is going to be exactly the same as if it were a simple struct (because the struct is anonymous):

ANSELbits.ANS4 = 0;

like image 938
alx Avatar asked Jan 27 '19 15:01

alx


People also ask

Can a union only have one member?

You can define a union with many members, but only one member can contain a value at any given time. Unions provide an efficient way of using the same memory location for multiple-purpose.

Can a structure be a member of union?

Both structure and union are the custom data types that store different types of data together as a single entity. The structure and union members can be objects of any type, such as other structures, unions, or arrays.

Can members of two different structures within the same program have same names?

Yes you can use the variable with same name in different structure. struct second { int x; int y; int the_same }; x,y and the_same are element of structure second. compiler will refer this variable with there structure name not individually..

What is anonymous union in C++?

An anonymous union is a union without a name. It cannot be followed by a declarator. An anonymous union is not a type; it defines an unnamed object. The member names of an anonymous union must be distinct from other names within the scope in which the union is declared.


1 Answers

It does not make any difference if you wrap and I suppose that someone has forgoten to add another member (or did not copy-paste everything) as in the declaration below. No warnings will be suppressed.

typedef union {
    struct {
        unsigned ANS0       :1;
        unsigned ANS1       :1;
        unsigned ANS2       :1;
        unsigned ANS3       :1;
        unsigned ANS4       :1;
        unsigned ANS5       :1;
        unsigned ANS6       :1;
    };
    uint8_t d8;
} ANSELbits_t;
extern volatile ANSELbits_t ANSELbits __at(0x09B);

BTW if the struct has to fit in 1 byte (8 bits) this declaration is wrong and uint_t type should be used instead.

like image 149
0___________ Avatar answered Nov 08 '22 09:11

0___________