0

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.

enter image description here

  • Does this answer your question? [":" (colon) in C struct - what does it mean?](https://stackoverflow.com/questions/8564532/colon-in-c-struct-what-does-it-mean) – StoneThrow Jan 18 '22 at 17:46
  • 1
    Initializing bitfields with numbers out of their range will cause problems. The 2-bit field m, for example, has only 4 legal values: 0, 1, -1, -2. It's then initialized to 5. – Lee Daniel Crocker Jan 18 '22 at 17:48

1 Answers1

2

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.

David Grayson
  • 84,103
  • 24
  • 152
  • 189