wahid_abdul
wahid_abdul

Reputation: 156

struct default values in c

I came across this problem in C using structs.I'm not sure of what is really happening here Thanks

#include<stdio.h>
int main()
{
 struct num1
 {
  int n1:2;
  int n2:3;
  int n3:4;
 };
 struct  num1 num={3,4,5};
 printf("%d %d %d\n",num.n1,num.n2,num.n3); 
 return 0;
}

The obtained output is

-1 -4 5

Upvotes: 1

Views: 485

Answers (1)

Barmar
Barmar

Reputation: 780984

These are bit fields, the number after the : specifies how many bits are in that member.

int n1:2

means a signed integer with 2 bits. In two's complement notation, this allows for values from -2 to 1; in sign+magnitude notation it allows for -1 to 1. When you try to assign 3 to this member, you get overflow, which results in undefined behavior.

Similarly

int n2:3

means a signied integer with 3 bits, whose range is -4 to 3 in two's complement, -3 to 3 in sign+magnitude, so assigning 4 causes overflow.

int n3:4

has a range from -8 to 7 or -7 to 7, so assigning 5 fits into it, so there's no overflow.

Upvotes: 6

Related Questions