what is the use of colon in the structure.
Code:int main ()
{
struct {
int p:4;
int k:4;
}l;
l.p=10;
l.k=1000;
printf("%d\n",l.p);
printf("%d\n",l.k);
return 0;
}
output:
-6
-8
Printable View
what is the use of colon in the structure.
Code:int main ()
{
struct {
int p:4;
int k:4;
}l;
l.p=10;
l.k=1000;
printf("%d\n",l.p);
printf("%d\n",l.k);
return 0;
}
output:
-6
-8
Had to do some testing, but it appears to limit the number of bits used to repsent the number.
As a test try this code out (adapted from the code you gave)
Did some more tests and here is what I've found. The struct will be allocated 4 bytes (32 bits) blocks for all the variables. So you could have 4 variables inside the struct that each only takes up 8 bits each and only use the orginal 4 byte block. However if you try to use 33 bits for all your variables then you will get another 4 byte block.Code:int main ()
{
struct {
int p:3;
int k:5;
int a:2;
}l;
int c;
for (c=0; c<20; ++c)
{
l.a=c;
l.p=c;
l.k=c;
printf("%d\t%d\t%d\t%d\n",c,l.p,l.k,l.a);
}
return 0;
}
So the following struct only takes 4 bytes
but the following takes 8 bytesCode:struct {
int a:4;
int b:4;
int c:8;
int d:8;
char ch;
}
Code:struct {
int a:5;
int b:4;
int c:8;
int d:8;
char ch;
}
Just look up bit fields in any good C book
good detective work thantos
Think I should get a new book? Its only copyrighted 1987 :D