Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Usage of signed vs unsigned variables for flags in C++

Tags:

c++

flags

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.

like image 591
Tomas Kubes Avatar asked Apr 22 '15 10:04

Tomas Kubes


1 Answers

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

like image 194
Sambuca Avatar answered Oct 18 '22 20:10

Sambuca