anonymous structures/unions in C with example

What are anonymous structures/unions?

Structures/unions with no names are called anonymous structures/unions. They are also called unnamed unions/structures.

As there are no names, we cannot create variables of anonymous structures/unions, but we can use them in nested structures or unions.

Real World Example of anonymous structures/unions:

A status register of a microcontroller can have multiple bits. Sometimes we read the value of each bit, and sometimes the whole register. We can use anonymous structure/unions in this to easily refer to both.

Code:


#include <stdio.h>
typedef union {
struct {
unsigned char c:1; //carry flag
unsigned char r:1; //reset flag
unsigned char o:1; //overflow flag
unsigned char s:1; //sign flag
unsigned char z:1; //zero flag
unsigned char i:1; //interrupt flag
unsigned char t:1; //timer flag
unsigned char n:1; //negative flag
};
unsigned char value;
}status_register;
int main()
{
status_register reg;
reg.c = 1;
reg.r = 1;
reg.n = 1;
printf("Status register value:0x%02x\n", reg.value);
}
view raw anonymous.c hosted with ❤ by GitHub

Output:

$ ./anonymous

Status register value:0x83

Comments

Popular posts from this blog

bb.utils.contains yocto

Difference between RDEPENDS and DEPENDS in Yocto

PR, PN and PV Variable in Yocto