Strange enum type conversion

Hajo Münzer hans-joachim.muenzer@gmx.de
Thu Dec 10 21:50:00 GMT 2009


Hi John,

You are right, on MSVC++ 0xffffffff is interpreted as unsigned int too,
not as -1. One major difference, however, is that enum elements are
always casted to (signed) int.

Thanks again to all and also for the references to the ISO standard to
Patrick!

Best Regards

Hajo


Am Dienstag, den 08.12.2009, 14:14 -0800 schrieb John (Eljay)
Love-Jensen:
> Hi Hajo,
> 
> > Is this defined somewhere in the C++ standard (where?) or is this gcc specific?
> 
> I believe it is defined in both ISO 14882 (C++) and in ISO 9899 (C).
> 
> I cannot cite chapter-and-verse at the moment.
> 
> > I was told that e. g. in MS Visual C++ 0xffffffff is interpreted as -1.
> 
> Shouldn't be.  I don't have MSVC++ handy to verify.  But you can test it yourself pretty quick.
> 
> Here's a variety of situations:
> ---------------
> #include <typeinfo>
> #include <iostream>
> int main()
> {
>   std::cout << typeid(signed int).name() << std::endl;
>   std::cout << typeid(unsigned int).name() << std::endl;
>   std::cout << typeid(0).name() << std::endl;
>   std::cout << typeid(0U).name() << std::endl;
>   std::cout << typeid(-1).name() << std::endl;
>   std::cout << typeid(~0U).name() << std::endl;
>   std::cout << typeid(0xFFFFFFFF).name() << std::endl;
>   std::cout << typeid(0x80000000).name() << std::endl;
>   std::cout << typeid(0xFFFFFFFFU).name() << std::endl;
>   std::cout << typeid(0x80000000U).name() << std::endl;
> }
> ---------------
> 
> > And what exactly happens, when the numbers in an enum are too large to fit into an signed int?
> 
> IIRC, on C, they are int or unsigned int.  (I'm not up to date on C99, so my understanding may be incorrect with C89, or no longer applicable with C99.)
> 
> On C++, the normal promotion rules apply.
> 
> > The compiler tries an unsigned int, then an long int then unsigned long and so on?
> 
> No.  Normal C++ promotion rules apply.
> 
> > Is this defined in the C++ standard or gcc specific?
> 
> ISO 14882 (C++)
> 
> > And is there a possibility to find out whether enum elements have signed or unsigned type?
> 
> Not sure.  There may be a GCC extension that lets a programmer test for signed/unsigned-ness.  There may be some template black magic to do the same.
> 
> > Thank you very much again,
> 
> You are very welcome.
> 
> Sincerely,
> --Eljay




More information about the Gcc-help mailing list