c - Structure member declaration with " : 1 " -


i found structure in linux kernel file include/sound/soc-dapm.h . confused declaration of members.i looked on google couldn't find informative stuff. if can explain why there :1 after every variable declaration,it great help. here part of code.

struct snd_soc_dapm_widget {      unsigned int off_val;                   /* off state value */     unsigned char power:1;                  /* block power status */     unsigned char invert:1;                 /* invert power bit */     unsigned char active:1;                 /* active stream on dac, adc's */     unsigned char connected:1;              /* connected codec pin */  } 

thanks.

it's called "bit field". it's memory optimization. lets store type in less space need otherwise.

(code above link).

#include <stdio.h> #include <string.h>  struct {   unsigned int age : 3; } age;  int main( ) {    age.age = 4;    printf( "sizeof( age ) : %d\n", sizeof(age) );    printf( "age.age : %d\n", age.age );     age.age = 7;    printf( "age.age : %d\n", age.age );     age.age = 8;    printf( "age.age : %d\n", age.age );     return 0; } 

outputs:

sizeof( age ) : 4 age.age : 4 age.age : 7 age.age : 0  

notice how assigning value higher 23 reduces size of age.age 0? because :3. means unsigned char active:1; example great storing booleans: can only true or false, can't accidentally store 255 (which happens maximum value of unsigned char).


Comments

  1. Hi

    Very useful and informative post. Thanks for sharing.

    Regards,
    Manish Garg

    ReplyDelete

Post a Comment

Popular posts from this blog

html - How to style widget with post count different than without post count -

How to remove text and logo OR add Overflow on Android ActionBar using AppCompat on API 8? -

javascript - storing input from prompt in array and displaying the array -