Reputation: 121
Following snippet from my zigbee wsndemo code is giving me hard time to understand the structure. I went through many structure related articles online but couldnt understand how these structure variables are define and can be used. Please help.
static struct
{
uint8_t appSubTaskPosted : 1;
uint8_t appCmdHandlerTaskPosted : 1;
uint8_t appMsgSenderTaskPosted : 1;
} appTaskFlags =
{
.appSubTaskPosted = false,
.appCmdHandlerTaskPosted = false,
.appMsgSenderTaskPosted = false
};
Upvotes: 6
Views: 2295
Reputation: 93556
You have not specified in your question exactly what it is you don't understand, but there are at least four things going on in your example that you might not find in "classic" C literature or from a general search in structures. These are:
Bitfields have always been in ISO/ANSI C, but are not commonly used. Although they can result in memory efficient data structures, on most architectures they generate a greater amount of code to access and accesses may not be atomic, which is an issue when the data is shared between interrupt or thread contexts. Also the packing of bitfields is implementation defined, so may result in non-portable code in applications where the exact bit position is critical (such as when overlaying a hardware register).
Designated initializers were introduced in ISO C99. There is not much C99 specific literature, most C literature pre-dates it or sticks to the C90 subset for compatibility. You should search for C99 specifically if you want to find information is such things.
Explicit width data types (uint8_t
in this case), were also introduced with C99 but are simply implemented as typedef
aliases of built-in types in the standard header stdint.h, so can be implemented in C90 compilers too.
Similarly the boolean literals true
and false
were introduced in C99 along with the bool
data type. In C99 bool
is a typedef
alias for _Bool
defined in stdbool.h
along with definitions for true
and false
. You can define bool
and true
and false
in C90 if you chose to, but it lacks the built-in _Bool
data type, so you would alias some other integral type.
Upvotes: 5
Reputation: 8861
They're bitfields, which in this case have 1 bit. They can only have the values 0 or 1, true or false. They take less memory than a bool
individually.
You can also define bitfields greater than 1. For example, a bitfield of 2 can have the values 0, 1, 2, and 3. The beauty of bitfields is you don't need an offset to access them which you would have to do if you were using a larger data type's individual bits.
If you're defining a structure with bitfields, define them right next to each other because bitfields like this actually share a larger data type, such as an int 32.
Upvotes: 5