开发者

Why Is C++ Issuing Warnings On Enums With Negative Values?

My current code resembles this:

enum Enum1 : signed __int8
{
    Value1 = 1 ,
    Value2 = 2 ,
    Value3 = -3  // C4341
} ;

The error details state:

"warning C4341: 'Value3' : signed value is 开发者_如何学Goout of range for enum constant"

MSDN states that this warning only occurs when you use values outside of the range of an int:

(> 2^31) OR (< 1 - 2^31)

Why is it telling me that my negative values are invalid? It is only a warning, but Google is telling me that this warning indicates that these enum values will be undefined - which will break my program.


Seems like a bug to me. The current 0x draft doesn't indicate that this should be the case, and neither does the MSDN documentation.


Your answer is basically described here: Are C++ enums signed or unsigned?

It is up to your compiler's implementation to define whether the value of the enum is signed or unsigned. I assume they left the warning there so that if you or someone else uses a different compiler, you may get different behavior.


I am using Microsoft Visual Studio 2010. Using "char" or "signed char" in place of "signed __int8" yields identical results - namely C4341 for "-3" and C4369 for 0xFD
This other MSDN article states clearly that the ": signed __int8" explicitly specifies the underlying type for the enumerators. This being said, it can be assumed that this warning exists simply for the purpose of making the developer aware of possible incompatibilities with other compilers.


Since someone mentioned it is compiler specific, it works with g++ as shown below

#include <stdio.h>

enum Enum1
{
    Value1 = 1 ,
    Value2 = 2 ,
    Value3 = -3
} ;

enum Enum1 myval;


main(){
    myval = Value3;
    printf("%d\n", myval);
}

compile: g++ negenum.cpp

result when running: -3

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜