| 89 | |
| 90 | A second way to initialize a bit-field is to use a constructor. For the sake of argument, suppose that every use of {{{bitfield_example_type}}} required the C element to be set to 1. Rather than trying to remember this requirement with every declaration of the bit-field, we can use a simple constructor function that enforces this requirement while still allowing us to set the A and B fields independently. Here is our constructor: |
| 91 | |
| 92 | {{{ |
| 93 | #!div style="font-size: 90%" |
| 94 | {{{#!C |
| 95 | bitfield_example_type constructor(bitfield_example_type bitfield_argument){ |
| 96 | bitfield_example_type my_bitfield; |
| 97 | |
| 98 | my_bitfield = bitfield_argument; |
| 99 | my_bitfield.C = 1; |
| 100 | |
| 101 | return my_bitfield; |
| 102 | } |
| 103 | }}} |
| 104 | }}} |
| 105 | |
| 106 | The following code shows how to use this constructor and then print the contents of the bit-field: |
| 107 | |
| 108 | {{{ |
| 109 | #!div style="font-size: 90%" |
| 110 | {{{#!C |
| 111 | bitfield_example_type my_bitfield; |
| 112 | my_bitfield = constructor( (bitfield_example_type){ .B = 27 } ); |
| 113 | print_bitfield_example_type( my_bitfield ); |
| 114 | }}} |
| 115 | }}} |
| 116 | |
| 117 | The above code uses an extremely useful syntax called a [https://gcc.gnu.org/onlinedocs/gcc/Designated-Inits.html designated initializer]. We can create a {{{bitfield_example_type}}} directly in the argument of our call to {{{constructor}}} by explicitly naming the fields we want assigned. In this case, we have set B to 27 and have chosen not to set either A or C. This will create a {{{bitfield_example_type}}} where both A and C are set to 0 but B is set to 27. Our constructor, however, should explicitly set the C field to be 1 according to our requirements. Here is the resulting print: |
| 118 | |
| 119 | {{{ |
| 120 | #!div style="font-size: 90%" |
| 121 | {{{ |
| 122 | bitfield_example_type Contents: |
| 123 | .raw_value = 0xB6 |
| 124 | .A = 0 |
| 125 | .B = 27 |
| 126 | .C = 1 |
| 127 | }}} |
| 128 | }}} |
| 129 | |
| 130 | This provides a concise way of initializing a bit-field where some fields are dynamic and need to change while other fields are required to be set a certain way every time. |