Initializing a Bit Struct

Initializing a Bit Struct

To initialize a struct that contains bit fields, simply use the ={0}partial initialization list:

 int main(){  struct MP3_HEADER   {       unsigned Sync:11;     unsigned Version:2;     unsigned Layer:2;     unsigned Protection:1;     unsigned Bitrate:4;     unsigned Frequency:2;     unsigned Padding:1;     unsigned Private:1;     unsigned ChannelMode:2;     unsigned ModeExtension:2;     unsigned Copyright:1;     unsigned Original:1;     unsigned Emphasis:2;   };  // create an instance and initialize it  MP3_HEADER header  = {0}; /*set all members to zero*/}

When you use a {0} partial initialization list, both C and C++ guarantee that all the members in the struct


Share the Post: