简体   繁体   中英

How do the bit-fields work exactly in these C programs?

I am a bit confused with the output of the following code although I know what the declaration of such struct means in C.

#include<stdio.h>

struct struc
{
    int a:1;
    int b:3;
    int c:6;
    int d:3;
}s1;

struct stru
{
    char a:3;
}s2;

int main()
{
    printf("%lu %lu",sizeof(s1),sizeof(s2));
    getchar();
    return 0;
}

I am trying to learn the actual working of this type of structure declaration. Can anyone explain how the code is giving output as "4 1", as I want to get the grasp over the concept properly.

And also the following code:

#include <stdio.h>

struct marks{
    int p:3;
    int c:3;
    int m:2;
};

int main(void) {
    struct marks s={2,-6,5};
    printf("%d %d %d",s.p,s.c,s.m);
    return 0;
}

What should be the output from this program?

The code you show is using bit fields . In a nutshell, :n after a struct member restricts this member to use only n bits, and such members are "packed" together when adjacent members have the same type .

A long time ago, this was sometimes useful to save memory -- nowadays, you might need it in very low-level hardware interfacing code, but that's probably about it.

What happens here:

struct struc
{
    int a:1;
    int b:3;
    int c:6;
    int d:3;
}s1;

This struct only has 1 + 3 + 6 + 3 = 13 bits worth of information. Assuming your implementation uses 32 bit int and a char has 8 bits, the sizeof int is 4 ( 32 / 8 ), and this is still enough to store all the bits of your members here. So the size of the whole struct is still only 4 .

Note that all of this is implementation defined -- it depends on the sizes of char and int and the compiler is still free to add padding as needed. So using bitfields requires you to know what exactly your implementation is doing, at least if you need to rely on sizes and the exact layout of the bits.

In the example we can see that the 1st struct uses int and the 2nd struct uses a char.

The char gives a size result of 1. Which I think is as expected.

If we look at the sizes of variables : cpp reference - types Then we can see that an int can take up 16 or 32 bits.

As size of your struct is 4 we can determine that your compiler uses 32 bits for this storage.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM