Click here to Skip to main content
15,894,405 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
C++
struct abc
{
  int a:3;
  int b:3;
  int c:2;
}
void main()
{
   struct abc a=(2,3,4)
   printf(" %d %d %d",a.a,a.b,a.c);
   gethc();
}
Posted
Updated 1-Mar-12 0:12am
v2

Modified code which runs

C#
struct abc
{
    int a:3;
    int b:3;
    int c:2;
};

int _tmain(int argc, _TCHAR* argv[])
{
    struct abc a = {2,3,4};
    printf(" %d %d %d, %d",a.a,a.b,a.c,sizeof(struct abc));
    return 0;
}


So here a is assigned 3 bits, b is assigned 3 bits and c is assigned 2 bits in your structure. Now when you give value to a structure variable.
Values provided in bit

a = 10 (2 in binary) (take 2 bit space out of three)
b = 11 (3 in binary) (take 2 bit space out of three)
c = 100 (4 in binary) (needs 3 bit space but have 2 bit only)

so value of a and b will be printed correctly, but value of c will be 0, as third bit from (100) that is 1 is not stored.
 
Share this answer
 
Comments
CPallini 1-Mar-12 6:14am    
Did you notice the fields have a signed type?
JackDingler 1-Mar-12 15:21pm    
Good catch. :)
This is a special kind of struct, called a bitfield.
The whole structure is stored in a single word, with the number after the colon indicating how many bits of that word are taken by each element. So "a" is 3 bits (0-7 inclusive), "b" is 3 bits, and "c" is 2 bits (0-3 inclusive). The added complication is that int is a signed type, so your value range is a lot smaller...
Your code won't compile, so there is no point in explaining it in detail! Fix your syntax errors first, then ask about specific problems.
 
Share this answer
 
C++
struct abc
{
int a:3;
int b:3;
int c:2;
}

Defines (note: the missing semicolon is a syntax error) three bit fields in the struct abc. All share the same type, namely signed integer, a and b are three bits long (they may hold the values {-4,-3,-2,-1,0,1,2,3}) while c is two bits long (it may hold the values {-2,-1,0,1}).

C++
struct abc a=(2,3,4)

The above line (again, the missing semicolon is a syntax error) initializes the instance a of the struct abc this way:
C++
a.a = 2;
a.b = 3;
a.c = 4; // NOTE: 4 is an out of range value for c


C++
printf(" %d %d %d",a.a,a.b,a.c);

The above line prints the values of the bit fields.

C++
gethc();

I don't know what it is. Do you mean getch(); instead?
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900