codeforrest's blog

By codeforrest, history, 6 years ago, In English
I was doing this question based on output.The code is depicted below. 
struct s
{
   unsigned a:5;
   unsigned b:5;
   unsigned c:5;
   unsigned d:5;
}v={1, 2};

main()
{
    printf("size of v = %d",sizeof(v));
    return 0;
}


The output of above code is "size of v = 4". I will be glad if someone could help how we are getting this 4 as output?Thanks in advance!
  • Vote: I like it
  • 0
  • Vote: I do not like it

»
6 years ago, # |
  Vote: I like it 0 Vote: I do not like it

Auto comment: topic has been updated by codeforrest (previous revision, new revision, compare).

»
6 years ago, # |
  Vote: I like it 0 Vote: I do not like it

Auto comment: topic has been updated by codeforrest (previous revision, new revision, compare).

»
6 years ago, # |
  Vote: I like it 0 Vote: I do not like it

How exactly the memory is allocated is compiler dependent. In this case the compiler assignes the first 20 bits to the four variables, and then fills it up with 12 empty bits, just to get a nice number. Computer processors are optimized for handling 1/ 2/ 4 / 8 byte integers, so this makes more sense than creating a 3 byte type.

Btw, is it really that hard to format code in a nice way?

#include<stdio.h>

struct s { 
    unsigned a:5;
    unsigned b:5; 
    unsigned c:5;
    unsigned d:5;
} v={1, 2};
    
int main() {
    printf("size of v = %d",sizeof(v));
    return 0;
}
  • »
    »
    6 years ago, # ^ |
      Vote: I like it 0 Vote: I do not like it

    Thanks for prompt reply! I haven't posted code in formatted way, previously.I have corrected now formatting.

»
6 years ago, # |
  Vote: I like it 0 Vote: I do not like it

Auto comment: topic has been updated by codeforrest (previous revision, new revision, compare).

»
6 years ago, # |
Rev. 4   Vote: I like it +8 Vote: I do not like it

Actually if 15 bits only are needs as follows, and the bit fields are declared using unsigned short, then the sizeof operator should return 2 (bytes), i.e. 16 bits.


typedef unsigned short bitfield; struct s { bitfield a: 5; bitfield b: 5; bitfield c: 5; } v;

If the same bit fields are declared using unsigned char, then the sizeof operator should return 3 (bytes), i.e. 24 bits, as the three bit fields are aligned to three consecutive bytes.

Check the output of the following test program


typedef unsigned char bitfield; struct s { bitfield a: 5; bitfield b: 5; bitfield c: 5; } v; union t { s x; unsigned char y[ 3 ]; write() const { for( int i = 0; i < 3; i++ ) cout << int( y[ i ] ) << ' '; cout << endl; } } w; int main() { ios_base::sync_with_stdio( false ), cin.tie( nullptr ), cout.tie( nullptr ); cout << "size of v = " << sizeof( v ) << endl; cout << "size of w = " << sizeof( w ) << endl; w.write(), w.x.a = 1, w.write(), w.x.b = 1, w.x.a = 0, w.write(), w.x.c = 1, w.x.b = 0, w.write(); }