Skip to content

Commit 15174c1

Browse files
author
Colin Robertson
authored
Merge pull request MicrosoftDocs#3779 from MicrosoftDocs/FromPublicMasterBranch
Confirm merge from FromPublicMasterBranch to master to sync with https://github.com/MicrosoftDocs/cpp-docs (branch master)
2 parents 3e6d434 + 73688e9 commit 15174c1

File tree

1 file changed

+18
-3
lines changed

1 file changed

+18
-3
lines changed

docs/c-language/c-bit-fields.md

Lines changed: 18 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -48,23 +48,24 @@ Bit fields defined as **`int`** are treated as **`signed`**. A Microsoft extensi
4848

4949
Bit fields are allocated within an integer from least-significant to most-significant bit. In the following code
5050

51-
```
51+
```C
5252
struct mybitfields
5353
{
5454
unsigned short a : 4;
5555
unsigned short b : 5;
5656
unsigned short c : 7;
5757
} test;
5858

59-
int main( void );
59+
int main( void )
6060
{
6161
test.a = 2;
6262
test.b = 31;
6363
test.c = 0;
64+
return 0;
6465
}
6566
```
6667
67-
the bits would be arranged as follows:
68+
the bits of `test` would be arranged as follows:
6869
6970
```
7071
00000001 11110010
@@ -73,6 +74,20 @@ cccccccb bbbbaaaa
7374
7475
Since the 8086 family of processors stores the low byte of integer values before the high byte, the integer `0x01F2` above would be stored in physical memory as `0xF2` followed by `0x01`.
7576
77+
The ISO C99 standard lets an implementation choose whether a bit field may straddle two storage instances. Consider this structure, which stores four bit fields that total 64 bits:
78+
79+
```C
80+
struct
81+
{
82+
unsigned int first : 9;
83+
unsigned int second : 7;
84+
unsigned int may_straddle : 30;
85+
unsigned int last : 18;
86+
} tricky_bits;
87+
```
88+
89+
A standard C implementation could pack these bit fields into two 32-bit integers. It might store `tricky_bits.may_straddle` as 16 bits in one 32-bit integer and 14 bits in the next 32-bit integer. The Windows ABI convention packs bit fields into single storage integers, and doesn't straddle storage units. The Microsoft compiler stores each bit field in the above example so it fits completely in a single 32-bit integer. In this case, `first` and `second` are stored in one integer, `may_straddle` is stored in a second integer, and `last` is stored in a third integer. The `sizeof` operator returns `12` on an instance of `tricky_bits`. For more information, see [Padding and alignment of structure members](padding-and-alignment-of-structure-members.md).
90+
7691
**END Microsoft Specific**
7792

7893
## See also

0 commit comments

Comments
 (0)