What is the ":" (two points) used for in the declaration of a member of a structure?

12

I saw this:

typedef struct {
    unsigned char a : 1;
    unsigned char b : 7;
} Tipo;

What does this statement mean? What is this 1 and 7?

    
asked by anonymous 20.01.2017 / 13:24

1 answer

15

Let's run this code to better understand:

#include <stdio.h>

typedef struct {
    unsigned char a : 1;
    unsigned char b : 7;
} Tipo;

int main(void) {
    Tipo x = { .a = 1, .b = 64 };
    printf("%d e %d\n", x.a, x.b);
    printf("%d\n", sizeof(Tipo));
}

See running on ideone . And at Coding Ground . Also put it on GitHub for future reference .

Try to put in the member a a value greater than 1. It does not work, it can only be 0 or 1. Already picked up why?

In the second print we see that the size of this structure is 1 byte. And now, did you kill?

The colon is used when the structure is used to assemble a bit string and each member is called bit field . So what comes after : is the amount of bits that that member contains. So the a can only have 0 or 1. It only has 1 bit. The same is true if you try to put more than 127 in% with% that only has 7 bits.

Ideally these structures should have a total multiple size of 8 to fit with a byte, but if there is no alignment according to compiler rules.

The possible types of members are specified as b , _Bool , signed int , and others specified by the compiler, which is what was used. It is often best to use universally defined types. Then it is better to% w_th of% than% w_th of%.

It is very common for this type of structure to be within a larger structure with other members.

It's also very common to use unsigned int . So you can access one union member as a single die and the other union member as a bit structure.

#include <stdio.h>

typedef union {
    char valor;
    struct {
        unsigned char a : 1;
        unsigned char b : 1;
        unsigned char c : 1;
        unsigned char d : 1;
        unsigned char e : 1;
        unsigned char f : 1;
        unsigned char g : 1;
        unsigned char : 1;
    } bits;
} Tipo;

int main(void) {
    Tipo x = { .valor = 87 };
    printf("%d %d %d %d %d %d %d", x.bits.a, x.bits.b, x.bits.c, x.bits.d, x.bits.e, x.bits.f, x.bits.g);
}

See running on ideone . And No Coding Ground . Also put it on GitHub for future reference .

Note that I showed another point. You are not required to identify all the bits. Of course not putting a name in some bit, or set of bits, will not be able to access its value directly and named.

    
20.01.2017 / 13:24