Why structure member seems to have an overflown value?

Viewed 54

In the code below, I get A = -1 as output. I guess, it's because I am overflowing the A-member which is of 3 bits. I have two questions in this regard:

  1. Shouldn't the compiler consider the last 3 bits and ignore the rest, for the member A? Why is the value negative ?
  2. If all the bits are considered, why do I get the value of B = 0 as output?

I was expecting A would be having a value of 7 but I am clearly misunderstanding something. Please help.

#include  <stdio.h>
typedef struct
{
  char A: 3;
  char B: 3;
  char C: 3;
}my_struct;
my_struct new_object = {0};

void main(void)
{
  new_object. A = 63;
  printf("A = %d\n", new_object.A);
  printf("B = %d\n", new_object.B);
}
1 Answers

I was expecting A would be having a value of 7

OK. 7 is 111 in binary. But you have a signed char (apparently, because you told us it came out as -1). So you need to do:

typedef struct
{
  unsigned char A: 3;
  unsigned char B: 3;
  unsigned char C: 3;
}my_struct;
Related