Search code examples
c++enumscastingstatic-cast

static_cast from enum to long yields different output depending on enum members


NOTE1: I have figured the problem before asking it here but I just want a discussion about this non-intuitive behavior in my opinion

NOTE2: This happens on gcc 7.5

#include <stdio.h>

enum lulu
{
        XXX=-2,//if I comment this it considers the enum as unsigned
               //and the cast to long is telling a totally different story
        AAA=10,
        BBB,
        CCC
};

int test_long(long param)
{
        printf("param=%ld\n",param);
        return 0;
}

int main(void)
{
        lulu l1 = AAA;
        lulu l2 = lulu(-AAA);
        printf("parameters to be cast to long: <%X> <%X>\n",l1,l2);
        test_long(static_cast<long>(l1));
        test_long(static_cast<long>(l2));
        int val1 = l1;
        int val2 = l2;

        printf("%d %d\n",val1,val2);

        int i = -6;
        test_long(static_cast<long>(i));
        return 0;
}

The problem is this static_cast is extremely non-intuitive.

In the above example if I compile it like described below I get the following:

# g++ -o long_cast -Wall long_cast.cpp
# ./long_cast
parameters to be cast to long: <A> <FFFFFFF6>
param=10
param=-10
10 -10
param=-6
#

but if I comment the XXX definition (a negative enum member) I get a totally different story

# ./long_cast
parameters to be cast to long: <A> <FFFFFFF6>
param=10
param=4294967286
10 -10
param=-6
#

What is the proper way to handle this?

I did an intermediate step in converting the value to int and then did the static cast.

Any other suggestions?


Solution

  • The solution, as stated in the code is to temporary convert to a signed integer variable and then make a static_cast to long.

    int val2 = l2;
    
    long lval2 = static_cast<long>(val2);