Implementing Flags

001  uint8_t some_flag_set; // file scope: initialized to 0
002  
003  #define FLAG_1 128
004  #define FLAG_2 64
005  #define FLAG_3 64
006  #define FLAG_4 32
007  #define FLAG_5 16
008  #define FLAG_6 8
009  #define FLAG_7 4
010  #define FLAG_8 2
011  
012  // alternative notation that makes it more obvious what these are about
013  // #define FLAG_1 (1 << 7)
014  // #define FLAG_2 (1 << 6)
015  // #define FLAG_3 (1 << 5)
016  // #define FLAG_4 (1 << 4)
017  // #define FLAG_5 (1 << 3)
018  // #define FLAG_6 (1 << 2)
019  // #define FLAG_7 (1 << 1)
020  // #define FLAG_8 (1 << 0)
021  
022  // function to check if a set of flags is raised
023  bool check(uint8_t flags, uint8_t set)
024  {
025      return ((set & flags) != 0);
026  }
027  
028  // function to set flags
029  void set(uint8_t flags, uint8_t *set)
030  {
031      *set |= flags;
032  }
033  
034  // function to unset a set of flags
035  void unset(uint8_t flags, uint8_t *set)
036  {
037      *set &= ^flags;
038  }
039  
040  // function that accepts various options using flags
041  void my_func(uint8_t flags)
042  {
043      set(flags, &some_flag_set);
044  }
045  
046  int main(int argc, char *argv[])
047  {
048      my_func(FLAG_1|FLAG_3|FLAG_5); 
049      if (check(FLAG_3, some_flag_set)) 
050          print("flag 3 is set\n");  
051  }