#include<iostream.h>
#include<conio.h>
struct marks
{
 int a:3;
 int b:3;
 int c:2;
};
int main()
{
clrscr();
 marks m={2,12,5};
 cout<<m.a<<m.b<<m.c;
 getch();
 return(0);
}

o/p is 2-41
i got how 2 and 1 came but didnt get how -4 came.
according to me it should have been
binary for 12=1100
b can store 3 bits so it should have been 4.

#include<iostream.h>
#include<conio.h>
struct marks
{
 int a:3;
 int b:3;
 int c:2;
};
int main()
{
clrscr();
 marks m={2,12,5};
 cout<<m.a<<m.b<<m.c;
 getch();
 return(0);
}

o/p is 2-41
i got how 2 and 1 came but didnt get how -4 came.
according to me it should have been
binary for 12=1100
b can store 3 bits so it should have been 4.

Keep in mind that these bit fields are by default signed. If you have 3 bits, and you load in 1100, then that is 4 with a sign bit which gives -4. If you declare b as unsigned, then it comes out as 4. The same with c, if you assign that 6 instead of 5, then you get -2. Apparently, the sign bit is not included in the number of bits declared for the bit field.

#include<iostream.h>
#include<conio.h>
struct marks
{
 int a:3;
 int b:3;
 int c:2;
};
int main()
{
clrscr();
 marks m={2,12,5};
 cout<<m.a<<m.b<<m.c;
 getch();
 return(0);
}

o/p is 2-41
i got how 2 and 1 came but didnt get how -4 came.
according to me it should have been
binary for 12=1100
b can store 3 bits so it should have been 4.

Read this on signed bit fields:

http://www.devx.com/tips/Tip/13991

This question has already been answered. Start a new discussion instead.