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:
Output:
$ ./anonymous
Status register value:0x83
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:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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); | |
} |
Output:
$ ./anonymous
Status register value:0x83
Comments
Post a Comment