0

I am a newbie in C and trying to understand the below structure that I came across.

typedef struct {
    char struct1_name[32];
    uint8_t is_initialized:1
} struct1_s;

I think instead of bool "uint8_t is_initialized:1" is used here. Just wondering what ":1" means? what the significance of this? I am sure this will be answered somewhere but I am not sure how to search for this, hence any link/example that describes the above one would be great

pmg
  • 106,608
  • 13
  • 126
  • 198
Hipster1206
  • 411
  • 6
  • 13
  • 3
    [Bit fields](https://en.cppreference.com/w/c/language/bit_field) – kaylum Oct 12 '20 at 10:30
  • 1
    Relatively off topic - The declaration is incomplete, you're missing the new name of the struct. – anastaciu Oct 12 '20 at 10:35
  • 1
    there are lots of duplicates: [What does a colon in a struct declaration mean, such as :1, :7, :16, or :32?](https://stackoverflow.com/q/1604968/995714), [“:” (colon) in C struct - what does it mean?](https://stackoverflow.com/q/8564532/995714), [What does a colon mean after a function in a struct](https://stackoverflow.com/q/41327404/995714) – phuclv Oct 12 '20 at 10:53
  • @phuclv 2 of the 3 questions you linked are not C but C++ questions. A C question is never a duplicate of a C++ question, this are 2 different languages. – 12431234123412341234123 Oct 12 '20 at 12:12

1 Answers1

0

the :1 is an explicit size in bits for the specified type.

example

so in this case you have a unsigned int with only 1 bit which is basically a bool as we know it

if it were :3 there would be three bits for it and you could store 'values' up to 7 in it but it being :1 can only store 0/1

It allows you to make types even smaller. E.G. a struct with 4 uints could be made to fit in a single byte this way


IIRC this only works for integer based types.

Daij-Djan
  • 49,552
  • 17
  • 113
  • 135
  • C standard says *A bit-field shall have a type that is a qualified or unqualified version of _Bool, signed int, unsigned int, or some other implementation-defined type. ...* Most compilers probably allow any integer type. – 12431234123412341234123 Oct 12 '20 at 12:15