What does this colon do in an enum declaration? - c++

I did a search for this question thinking that somebody must have asked it before. I did not turn up any results, so if it has been, please post the link and feel free to close the question.
I ran across this code in EASTL:
enum : size_type { // size_type = size_t
npos = (size_type)-1,
kMaxSize = (size_type)-2
};
I have never encountered an enum declaration like that. What does the : do in this case?

In C++0x, you can specify the underlying type for the enum. In this case, it will be size_type.
(And it may be supported as an extension in other places prior to C++0x, obviously.)

This is a Microsoft extension that lets you choose the base type of the enum values. For example, this lets you specify that values are unsigned (Microsoft's compilers usually choose signed by default) or that they only occupy 8 or 16 bits (Microsoft normally defaults to 32 bits).
The syntax is documented here: http://msdn.microsoft.com/en-us/library/2dzy4k6e(v=VS.100).aspx but I'm not able to find official documentation of what it actually does.
C++11 adds a similar feature, but with slightly different syntax. In C++11 you'd write it like this:
enum MyEnum : size_type { .. values .. };

Related

Ask about new syntax of enum (C++) [duplicate]

I did a search for this question thinking that somebody must have asked it before. I did not turn up any results, so if it has been, please post the link and feel free to close the question.
I ran across this code in EASTL:
enum : size_type { // size_type = size_t
npos = (size_type)-1,
kMaxSize = (size_type)-2
};
I have never encountered an enum declaration like that. What does the : do in this case?
In C++0x, you can specify the underlying type for the enum. In this case, it will be size_type.
(And it may be supported as an extension in other places prior to C++0x, obviously.)
This is a Microsoft extension that lets you choose the base type of the enum values. For example, this lets you specify that values are unsigned (Microsoft's compilers usually choose signed by default) or that they only occupy 8 or 16 bits (Microsoft normally defaults to 32 bits).
The syntax is documented here: http://msdn.microsoft.com/en-us/library/2dzy4k6e(v=VS.100).aspx but I'm not able to find official documentation of what it actually does.
C++11 adds a similar feature, but with slightly different syntax. In C++11 you'd write it like this:
enum MyEnum : size_type { .. values .. };

'=' should initialize either all enum members or only the first;

I am trying to build my code with following enum values :
typedef enum {
YUV_420P=0,
YUV_422P,
RGB_P,
BAYER_P,
YUV_422IBE,
YUV_444IBE,
A_1BIT,
YUV_420SP,
COMPLEX_8BIT,
COMPLEX_16BIT,
COMPLEX_32BIT,
COMPLEX_U8BIT,
COMPLEX_U16BIT,
COMPLEX_U32BIT,
ALPHA_TYPE=0x8000
} Format;
But during building I am getting the below linting warning ..
sample.h: Note 960: Violates MISRA 2004 Required Rule 9.3, '=' should initialize either all enum members or only the first; enumerator: 'ALPHA_TYPE' ..
I don't want to change value of ALPHA_TYPE and I want to put the ALPHA_TYPE in this enum only. How can I resolve this?
Your code already does what you want. You just need to suppress this particular warning.
On the other hand, if you absolutely do need to adhere to this MISRA 2004 rule 9.3, then you will need to change your code and find a different solution. But you cannot have it both ways.
If values of other enums does not matter, you can do this
typedef enum {
ALPHA_TYPE=0x8000,
YUV_420P,
YUV_422P,
RGB_P,
BAYER_P,
YUV_422IBE,
YUV_444IBE,
1BIT,
YUV_420SP,
COMPLEX_8BIT,
COMPLEX_16BIT,
COMPLEX_32BIT,
COMPLEX_U8BIT,
COMPLEX_U16BIT,
COMPLEX_U32BIT
} Format;
Or
Define all your enum values like this (this avoid one of your enum value to change, if you add a new one)
typedef enum {
YUV_420P=0,
YUV_422P=1,
RGB_P=2,
BAYER_P=3,
YUV_422IBE=4,
YUV_444IBE=5,
1BIT=6,
YUV_420SP=7,
COMPLEX_8BIT=8,
COMPLEX_16BIT=9,
COMPLEX_32BIT=10,
COMPLEX_U8BIT=11,
COMPLEX_U16BIT=12,
COMPLEX_U32BIT=13,
ALPHA_TYPE=0x8000
} Format;
This is certainly not a C++ requirement.
[C++11: 7.2/2]: An enumerator-definition with = gives the associated enumerator the value indicated by the constant-expression. If the first enumerator has no initializer, the value of the corresponding constant is zero. An enumerator-definition without an initializer gives the enumerator the value obtained by increasing the value of the previous enumerator
by one.
The grammar above it allows multiple enumerators to have an initializer.
If you are allowed, perhaps you can turn off checks for compliance with this "MISRA 2004" rule. You could also simply ignore it since it appears to be a mere Note. Personally I would be a bit annoyed to have that popping up all the time, but perhaps that's just me.
Since the first enum value is 0, and since it is that also by default, simply use the default. ← I misread the warning, this point is not a solution.
And/or, turn off the MISRA rule checking.
And/or, ignore the specific note. Apparently you can do that via an +esym option. Or maybe -esym, just try out things and check the documentation.

enum declaration in windows to linux

I have a C++ declaration:
enum SETTINGS:UINT32
{
a=1,
b=2,
};
what is the meaning of :UINT32?
how can I swich this declaration to linux?
Its part of the new C++0x way of declaring enums
enum <EnumTypeName> [: <Optinal-Type>] { <ValueList> };
By default an enum is represented by an integer.
The new syntax allows you to optionally define the type used to represent the enum
In this case it indicates that the enum underlying representation should be of type UINT32. What this means will depend on what the macro UINT32 has been defined to be. But it is probably an integer of at least 32 bits and is unsigned. :-)
See Bjornes description of the new enum stuff:
http://www2.research.att.com/~bs/C++0xFAQ.html#enum
Here, the :UINT32 syntax specifies the underlying enum type. However, this is not standard C++ (at least, not standard C++03) but a Visual Studio extension : g++ will probably reject it, and you should too.
See C++ Enumeration Declaration on MSDN for a description of this syntax
See this Wikipedia page regarding C++0x upcoming changes to enum declarations
EDIT As pointed in the comments by Martin York, g++ supports this syntax since version 4.4, so I guess the only issue for a Linux portage would be UINT32 being non standard.
u = unsigned
int = integer
32 = 32 bit
read this : "Uint32", "int16" and the like; are they standard c++?

Do all C++ compilers allow using a static const int class member variable as an array bound?

In VC++ when I need to specify an array bound for a class member variable I do it this way:
class Class {
private:
static const int numberOfColors = 16;
COLORREF colors[numberOfColors];
};
(please don't tell me about using std::vector here)
This way I have a constant that can be used as an array bound and later in the class code to specify loop-statement constraints and at the same time it is not visible anywhere else.
The question is whether this usage of static const int member variables only allowed by VC++ or is it typically allowed by other widespread compilers?
This is valid C++ and most (all?) reasonably modern compilers support it. If you are using boost, you can get portable support for this feature in the form of BOOST_STATIC_CONSTANT macro:
class Class {
private:
BOOST_STATIC_CONSTANT(int, numberOfColors = 16);
COLORREF colors[numberOfColors];
};
The macro is expanded to static const int numberOfColors = 16 if the compiler supports this, otherwise it resorts to enum { numberOfColors=16 };.
That behavior is valid according to the C++ Standard. Any recent compiler should support it.
I believe that Visual Studio 2005 and beyond supports it. The XCode C++ compiler as well (this is gcc actually).
If you want to be safe you could always use the old enum hack that I learned from Effective C++. It goes like this:
class Class {
private:
enum {
numberOfColors = 16
};
COLORREF colors[numberOfColors];
};
Hope this helps.
This has been standard C++ for more than a decade now. It's even supported by VC -- what more could you want? (#Neil: What about SunCC? :^>)
Yes, it's 100% legal and should be portable. The C++ standard says this in 5.19 - Constant expressions" (emphasis mine):
In several places, C++ requires expressions that evaluate to an integral or enumeration constant: as array bounds (8.3.4, 5.3.4), as case-expressions (6.4.2), as bit-field lengths (9.6), as enumerator initializers (7.2), as static member initializers (9.4.2), and as integral or enumeration non-type template arguments (14.3).
constant-expression:
conditional-expression
An integral constant-expression can involve only literals (2.13), enumerators, const variables or static data members of integral or enumeration types initialized with constant expressions (8.5), non-type template parameters of integral or enumeration types, and sizeof expressions.
That said, it appears that VC6 doesn't support it. See StackedCrooked's answer for a good workaround. In fact, I generally prefer the enum method StackedCrooked mentions for this type of thing.
As an FYI, the "static const" technique works in VC9, GCC 3.4.5 (MinGW), Comeau and Digital Mars.
And don't forget that if you use a "`static const'" member, you'll need a definition for it in addition to the declaration strictly speaking. However, virtually all compilers will let you get away with skipping the definition in this case.
Besides other answers you can use following function do determine number of elements in statically alocated arrays:
template<typename T, size_t length>
size_t arrayLength(T (&a)[length])
{
return length;
}
I'm pretty sure that this will also work with gcc and Solaris, but I can't verify this at the moment.
In the future you could extend the idea like this:
template<int size>
class Class {
private:
COLORREF colors[size];
};
and use it like this:
Class<5> c;
so that you are not limited to exactly one buffer size in your application.
I've stopped bothering about the portability of that years ago. There are perhaps still compilers which don't support it, but I haven't met any of them recently.
It is possible to answer questions like this by referencing the ISO C++ speicifcation but the spec is hard for people to get and harder to read.
I think the simplest answer hinges on two things:
Microsoft Visual Studio 2005 and up is a relatively conformant C++ implementation. If it allows you to do something, chances are its standard.
Download something like Code::Blocks to get a GCC compiler to try stuff out. If it works in MS and GCC, chances really are, its standard.

Difference between Enum and Define Statements

What's the difference between using a define statement and an enum statement in C/C++ (and is there any difference when using them with either C or C++)?
For example, when should one use
enum {BUFFER = 1234};
over
#define BUFFER 1234
enum defines a syntactical element.
#define is a pre-preprocessor directive, executed before the compiler sees the code, and therefore is not a language element of C itself.
Generally enums are preferred as they are type-safe and more easily discoverable. Defines are harder to locate and can have complex behavior, for example one piece of code can redefine a #define made by another. This can be hard to track down.
#define statements are handled by the pre-processor before the compiler gets to see the code so it's basically a text substitution (it's actually a little more intelligent with the use of parameters and such).
Enumerations are part of the C language itself and have the following advantages.
1/ They may have type and the compiler can type-check them.
2/ Since they are available to the compiler, symbol information on them can be passed through to the debugger, making debugging easier.
Enums are generally prefered over #define wherever it makes sense to use an enum:
Debuggers can show you the symbolic name of an enums value ("openType: OpenExisting", rather than "openType: 2"
You get a bit more protection from name clashes, but this isn't as bad as it was (most compilers warn about re#defineition.
The biggest difference is that you can use enums as types:
// Yeah, dumb example
enum OpenType {
OpenExisting,
OpenOrCreate,
Truncate
};
void OpenFile(const char* filename, OpenType openType, int bufferSize);
This gives you type-checking of parameters (you can't mix up openType and bufferSize as easily), and makes it easy to find what values are valid, making your interfaces much easier to use. Some IDEs can even give you intellisense code completion!
Define is a preprocessor command, it's just like doing "replace all" in your editor, it can replace a string with another and then compile the result.
Enum is a special case of type, for example, if you write:
enum ERROR_TYPES
{
REGULAR_ERR =1,
OK =0
}
there exists a new type called ERROR_TYPES.
It is true that REGULAR_ERR yields to 1 but casting from this type to int should produce a casting warning (if you configure your compiler to high verbosity).
Summary:
they are both alike, but when using enum you profit the type checking and by using defines you simply replace code strings.
It's always better to use an enum if possible. Using an enum gives the compiler more information about your source code, a preprocessor define is never seen by the compiler and thus carries less information.
For implementing e.g. a bunch of modes, using an enum makes it possible for the compiler to catch missing case-statements in a switch, for instance.
enum can group multiple elements in one category:
enum fruits{ apple=1234, orange=12345};
while #define can only create unrelated constants:
#define apple 1234
#define orange 12345
#define is a preprocessor command, enum is in the C or C++ language.
It is always better to use enums over #define for this kind of cases. One thing is type safety. Another one is that when you have a sequence of values you only have to give the beginning of the sequence in the enum, the other values get consecutive values.
enum {
ONE = 1,
TWO,
THREE,
FOUR
};
instead of
#define ONE 1
#define TWO 2
#define THREE 3
#define FOUR 4
As a side-note, there is still some cases where you may have to use #define (typically for some kind of macros, if you need to be able to construct an identifier that contains the constant), but that's kind of macro black magic, and very very rare to be the way to go. If you go to these extremities you probably should use a C++ template (but if you're stuck with C...).
If you only want this single constant (say for buffersize) then I would not use an enum, but a define. I would use enums for stuff like return values (that mean different error conditions) and wherever we need to distinguish different "types" or "cases". In that case we can use an enum to create a new type we can use in function prototypes etc., and then the compiler can sanity check that code better.
Besides all the thing already written, one said but not shown and is instead interesting. E.g.
enum action { DO_JUMP, DO_TURNL, DO_TURNR, DO_STOP };
//...
void do_action( enum action anAction, info_t x );
Considering action as a type makes thing clearer. Using define, you would have written
void do_action(int anAction, info_t x);
For integral constant values I've come to prefer enum over #define. There seem to be no disadvantages to using enum (discounting the miniscule disadvantage of a bit more typing), but you have the advantage that enum can be scoped, while #define identifiers have global scope that tromps everything.
Using #define isn't usually a problem, but since there are no drawbacks to enum, I go with that.
In C++ I also generally prefer enum to const int even though in C++ a const int can be used in place of a literal integer value (unlike in C) because enum is portable to C (which I still work in a lot) .
If you have a group of constants (like "Days of the Week") enums would be preferable, because it shows that they are grouped; and, as Jason said, they are type-safe. If it's a global constant (like version number), that's more what you'd use a #define for; although this is the subject of a lot of debate.
In addition to the good points listed above, you can limit the scope of enums to a class, struct or namespace. Personally, I like to have the minimum number of relevent symbols in scope at any one time which is another reason for using enums rather than #defines.
Another advantage of an enum over a list of defines is that compilers (gcc at least) can generate a warning when not all values are checked in a switch statement. For example:
enum {
STATE_ONE,
STATE_TWO,
STATE_THREE
};
...
switch (state) {
case STATE_ONE:
handle_state_one();
break;
case STATE_TWO:
handle_state_two();
break;
};
In the previous code, the compiler is able to generate a warning that not all values of the enum are handled in the switch. If the states were done as #define's, this would not be the case.
enums are more used for enumerating some kind of set, like days in a week. If you need just one constant number, const int (or double etc.) would be definetly better than enum. I personally do not like #define (at least not for the definition of some constants) because it does not give me type safety, but you can of course use it if it suits you better.
Creating an enum creates not only literals but also the type that groups these literals: This adds semantic to your code that the compiler is able to check.
Moreover, when using a debugger, you have access to the values of enum literals. This is not always the case with #define.
While several answers above recommend to use enum for various reasons, I'd like to point out that using defines has an actual advantage when developing interfaces. You can introduce new options and you can let software use them conditionally.
For example:
#define OPT_X1 1 /* introduced in version 1 */
#define OPT_X2 2 /* introduced in version 2 */
Then software which can be compiled with either version it can do
#ifdef OPT_X2
int flags = OPT_X2;
#else
int flags = 0;
#endif
While on an enumeration this isn't possible without a run-time feature detection mechanism.
Enum:
1. Generally used for multiple values
2. In enum there are two thing one is name and another is value of name name must be distinguished but value can be same.If we not define value then first value of enum name is 0 second value is 1,and so on, unless explicitly value are specified.
3. They may have type and compiler can type check them
4. Make debugging easy
5. We can limit scope of it up to a class.
Define:
1. When we have to define only one value
2. It generally replace one string to another string.
3. It scope is global we cannot limit its scope
Overall we have to use enum
There is little difference. The C Standard says that enumerations have integral type and that enumeration constants are of type int, so both may be freely intermixed with other integral types, without errors. (If, on the other hand, such intermixing were disallowed without explicit casts, judicious use of enumerations could catch certain programming errors.)
Some advantages of enumerations are that the numeric values are automatically assigned, that a debugger may be able to display the symbolic values when enumeration variables are examined, and that they obey block scope. (A compiler may also generate nonfatal warnings when enumerations are indiscriminately mixed, since doing so can still be considered bad style even though it is not strictly illegal.) A disadvantage is that the programmer has little control over those nonfatal warnings; some programmers also resent not having control over the sizes of enumeration variables.