Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to make `enum` type to be unsigned?

Tags:

c++

enums

Is there a way to make enum type to be unsigned? The following code gives me a warning about signed/unsigned comparison.

enum EEE {
    X1 = 1
};

int main()
{
    size_t x = 2;
    EEE t = X1;
    if ( t < x ) std::cout << "ok" << std::endl;

    return 0;
}

I've tried to force compiler to use unsigned underlying type for enum with the following:

enum EEE {
    X1 = 1,
    XN = 18446744073709551615LL
    // I've tried XN = UINT_MAX (in Visual Studio). Same warning.
};

But that still gives the warning.


Changing constant to UINT_MAX makes it working in GNU C++ as should be according to the standard. Seems to be a bug in VS. Thanks to James for hint.

like image 767
Kirill V. Lyadvinsky Avatar asked Apr 28 '10 18:04

Kirill V. Lyadvinsky


1 Answers

You might try:

enum EEE {
    X1 = 1,
    XN = -1ULL
};

Without the U, the integer literal is signed.

(This of course assumes your implementation supports long long; I assume it does since the original question uses LL; otherwise, you can use UL for a long).

like image 180
James McNellis Avatar answered Nov 13 '22 06:11

James McNellis