开发者

What is the return type of enum |?

enum FileOpenFlags
{
    FileOpenFlags_Create = 1,
    FileOpenFlags_Truncate = 2,
};


FileOpenFlags flags = FileO开发者_JS百科penFlags_Create | FileOpenFlags_Truncate;

Is it true the return type of enum | is also enum??


No, the above expression will have the type int. However, since enums convert to and from int without problems, it's then implicitly converted back to enum for the store.

See also this comp.lang.c FAQ entry.


no it doesn't and c doesn't really care. You can still assign it to an enum even if the value returned by enum | enum is doesn't match the value of any enum you have defined.

They are all ints as far as c is concerned


An enum value is just an integer and operations on enum values are not guaranteed to return a defined enum value.


I usually define flags using #define,

#define FLAG_1 0x1
#define FLAG_2 0x2
#define FLAG_3 0x4

...

If you use enums and want seperate flags that can be OR'ed together, you would have to assign them a value using the '=' operator.


In this case you should not really be storing the union of those two back into an enum type - since the new value is not a valid value for that enum! Store them into an int, instead.

Alternatively, take a look at the c bit field types (wikipedia)

struct FOF {
  int Create : 1;
  int Truncate : 1;
};


I think this is valid, (int)3 should be returned in your example.

As far as I'm concerned, C treats enum values as type int via an internal cast or something along these lines. The thing with enums is that in C++ they can't be the LVALUE of an operation (because they're not treated as numbers), so you can't increment them or assign them a value. OTOH, you can always use them as the RVALUE (both in C and C++), so:

int flags = FileOpenFlags_Create | FileOpenFlags_Truncate; 

is valid in both C and C++, while

FileOpenFlags flags = FileOpenFlags_Create | FileOpenFlags_Truncate;

will probably work in C, but fail miserably in C++ ;)

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜