Is there any "good practice" or habit of using signed variables vs unsigned variables for flags? Personally I would use unsigned variable, but I can see even signed variable used for flags in some code. I mean especially in library interface where it matters.
UDPATE I cannot accept answer "use Enum", because it is implementation dependent and this it cannot be used in library interface.
I think an unsigned type is a better representation of a set of flags. Since you need a specific amount of equivalent bits to represent your flags. In a signed type the first bit is kind of special.
Probably the std::bitset could also meet your requirements. And will serve you with the basic logical operators and conversion methods.
#include <iostream>
#include <bitset>
using namespace std;
int main() {
std::bitset<4> flags;
flags.set(1);
flags.set(3);
std::cout << flags.to_string() << std::endl;
std::cout << flags.to_ulong() << std::endl;
return 0;
}
DEMO
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With