C programming

The following snippet from my wsndemo zigbee code gives me a hard time understanding the structure. I looked through many articles related to structure, but I could not understand how these structural variables are defined 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 }; 
+6
source share
2 answers

These are bit codes, which in this case have 1 bit. They can only have values ​​0 or 1, true or false. They consume less memory than bool individually.

You can also define bit fields greater than 1. For example, bit field 2 can have values ​​0, 1, 2, and 3. The beauty of bit fields is that you do not need an offset to access them, which you must do if you use larger individual data types.

If you define a structure with bit fields, define them next to each other, because bit fields like this have a common data type, for example, int 32.

+5
source

You did not indicate in your question exactly what you do not understand, but in your example there are at least four things that you cannot find in the β€œclassical” literature of C or from a general search in structures. These are:

  • Bit field members
  • Assigned Initializers
  • Explicit Width Data Types
  • Boolean constants

Battlefields have always been in ISO / ANSI C, but are usually not used. Although they can lead to efficient data structures with memory, on most architectures they generate more code for access and access, they may not be atomic, which is a problem when sharing data between interrupted or streaming contexts. In addition, the packing of bitfields is determined by the implementation, therefore, it can lead to intolerable code in applications where the exact bit position is important (for example, when superimposing a hardware register).

Assigned initializers have been introduced in ISO C99. There is not much specific literature on C99, most C literature prescribes it in advance or adheres to a subset of C90 for compatibility. You have to look for the C99 specifically if you want to find information - these are the things.

Explicit width data types ( uint8_t in this case) have also been introduced with C99, but are simply implemented as typedef built-in aliases in the standard stdint.h header, so they can be implemented in C90 compilers too.

Similarly, C99 introduced the boolean literals true and false , as well as the bool data type. C99 bool has a typedef alias for _Bool defined in stdbool.h , as well as definitions for true and false . You can define bool and true and false in C90 if you choose this, but it lacks the _Bool built-in data _Bool , so you should use a different type of integral.

+5
source

All Articles