简体   繁体   中英

Can somebody please explain me the logic behind this code?

Here is the code

#include <stdio.h>
#include <stdlib.h>

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

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

    return 0;
}

Especially the variable: number; , s{values}; and the relationship between them. I am new to C, so please go easy on me.

Here is the output of the code.

在此处输入图像描述

Inside the struct definition, the line int p:3; defines p as a bit field with 3 bits. Additionally, since the type on the left side ( int ) is signed, that means p will be a signed bit field. So it can hold values from -4 to 3. It probably uses two's complement on your computer, so the correspondence between bits and values is:

Bits of p Value
100 -4
101 -3
110 -2
111 -1
000 0
001 1
010 2
011 3

The line struct marks s={2,-6,5}; is basically equivalent to the following code (although sometimes there is a difference in warnings/errors emitted by the compiler):

struct marks s;
s.p = 2;
s.c = -6;
s.m = 5;

Since c and m do not have enough bits to hold the values being assigned to them here, your implementation will have to modify the values before storing them in those variables. Usually this is done by truncating the high bits. So -6 (11111010 in binary) becomes 2 (010) when we cram it into a 3-bit field, while 5 (00000101) becomes 1 (01) when we cram it into a 2-bit field.

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