c++ - bitwise flags get set arbitrarily -


i've been studying c++ (and programming matter) week, question may lack understanding of fundamental programming principles, here goes nothing:

unsigned int bitflags() { unsigned char option1 = 0x01; // hex 0000 0001 unsigned char option2 = 0x02; // hex 0000 0010 unsigned char option3 = 0x04; // hex 0000 0100 unsigned char option4 = 0x08; // hex 0000 1000 unsigned char option5 = 0x10; // hex 0001 0000 unsigned char option6 = 0x20; // hex 0010 0000 unsigned char option7 = 0x40; // hex 0100 0000 unsigned char option8 = 0x80; // hex 1000 0000  unsigned char myflags; // byte-size value hold combination of above 8 options  myflags |= option1|option2|option3;  if (myflags&option8)     return 1; else     return 0; }  int main() {    std::cout << bitflags() << "\n";     return 0; } 

so, set 3 flags (option1, option2, option3). now, flag query works expected (returns 1 options 1/2/3, , 0 rest) up-until option7/8. though option7/8 not set, function returns 1. brings me conclusion unsigned char myflags looks in binary: 1100 0000. then,

1) what's happening here? why 2 bits in use? how unsigned char using 2 bits in first place? shouldn't "highest" bit reserved signed variables?

2) why use bitwise assignment operator |= set bitflags when provides unexpected results. if assign myflags = option3 | option2 | option3 works expected - query option7/8 returns 0.

(there's high probability have no idea i'm talking about!)

you did not initialize myflags 0 there unknown junk in there before or in flags.


Comments

Popular posts from this blog

google chrome - Developer tools - How to inspect the elements which are added momentarily (by JQuery)? -

angularjs - Showing an empty as first option in select tag -

php - Cloud9 cloud IDE and CakePHP -