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

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.

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 .. };

"control reaches end of non-void function" with fully handled case switch over an enum type

Why does this code trigger a "control reaches end of non-void function" even if all possible values of type_t are handled? What is the best way to take care of this warning? Adding a return -1 after the switch?(Code tested here)
typedef enum {
A,
B
} type_t;
int useType(type_t x) {
switch (x) {
case A:
return 0;
case B:
return 1;
}
}
Related: Detecting if casting an int to an enum results into a non-enumerated value
In general, enums are not exclusive. Someone could call your function like useType( (type_t)3 ); for example. This is mentioned specifically in C++14 [dcl.enum]/8:
It is possible to define an enumeration that has values not defined by any of its enumerators.
Now, there are a bunch of rules about exactly which other values are possible for which other sorts of enum.
There are two categories of enum. The first is fixed underlying type, e.g. enum type_t : int, or enum class type_t . In those cases all values of the underlying type are valid enumerators.
The second is not fixed underlying type, which includes pre-C++11 enums such as yours. In this case the rule about values can be summarized by saying: compute the smallest number of bits necessary in order to store all values of the enum; then any number expressible in that number of bits is a valid value.
So - in your specific case, a single bit can hold both values A and B, so 3 is not valid value for the enumerator.
But if your enum were A,B,C, then even though 3 is not listed specifically, it is a valid value by the above rule. (So we can see that almost all enums will not be exclusive).
Now we need to look at the rule for what happens if someone does actually try to convert 3 to type_t. The conversion rule is C++14 [expr.static.cast]/10, which says that an unspecified value is produced.
However, CWG issue 1766 recognized that the C++14 text was defective and has replaced it with the following:
A value of integral or enumeration type can be explicitly converted to a complete enumeration type. The value is unchanged if the original value is within the range of the enumeration values (7.2). Otherwise, the behavior is undefined.
Therefore, in your specific case of exactly two enumerators with value 0 and 1, no other value is possible unless the program has already triggered undefined behaviour, so the warning could be considered a false positive.
To remove the warning, add a default: case that does something. I'd also suggest, in the interest of defensive programming, that it's a good idea to have a default case anyway. In practice it may serve to 'contain' the undefined behaviour: if someone does happen to pass an invalid value then you can throw or abort cleanly.
NB: Regarding the warning itself: it's impossible for a compiler to accurately warn if and only if control flow would reach the end of a function , because this would require solving the halting problem.
They tend to err on the side of caution: the compiler will warn if it is not completely sure, meaning that there are false positives.
So the presence of this warning does not necessarily indicate that the executable would actually allow entry into the default path.
To answer the second question ("What is the best way to take care of this warning?"):
In my eyes, typically, the best method is to add a call to __builtin_unreachable() after the switch statement (available both in GCC and Clang - maybe at some point we'll get [[unreachable]]).
This way, you explicitly tell the compiler that the code never runs over the switch statement. And if it does, you are happy to accept all dire consequences of undefined behaviour. Note that the most obvious reason to run over would be an enum containing a value that is not listed - which is undefined behaviour anyway as pointed out in the answer by #M.M.
This way, you get rid of the warning on current versions of both GCC and Clang without introducing new warnings.
What you lose is the protection by the compiler if you miss a valid situation that does run over the switch statement. This is mitigated to some degree that both GCC and Clang do warn you if miss a switch case completely (e.g. if a value gets added to the enum), but not if one of the cases runs into a break statement.

Why do I have to cast an enum element when assigning it to a same enum variable type in C?

I have the following:
typedef enum
{
FLS_PROG_SUCCESS,
FLS_PROG_FAIL,
FLS_ERASE_SUCCESS2U,
FLS_ERASE_FAIL,
FLS_READ_SUCCESS,
FLS_READ_FAIL,
FLS_FORMAT_SUCCESS,
FLS_FORMAT_FAIL
}FLS_JobResult_t;
void Foo(void)
{
FLS_JobResult_t ProgramStatus;
/* Then I try to initialize the variable value */
ProgramStatus = FLS_PROG_SUCCESS;
...
}
Innocent uh, but when compiling MISRA C gives the error:
The value of an expression shall not be assigned to an object with a narrower essential type or of a different essential type category
And I found out that I shall write the initialization as follows:
ProgramStatus = (FLS_JobResult_t)FLS_PROG_SUCCESS;
And this just doesn't look good to me, it's like MISRA wants me to throw casts in all the code and that's too much.
Do you know why is this? I don't think this should be an issue but I've tried everything that comes to my mind and this was the only way of getting rid of this error, but it simply does not make any sense, does it?
Regards.
(Hi, this is a new account so I cannot use the comments section yet to ask for further clarification, so, my answer may be broader than needed)
Based on the text of the warning message I assume you are talking about MISRA-C:2012 (the latest standard) which is a great improvement over the prior ones in that much more effort in stating the rationale along with many more compliant and non-compliant examples have been added. This being Rule 10.3, the rationale is: since C permits assignments between different arithmetic types to be performed automatically, the use of these implicit conversions can lead to unintended results, with the potential for loss of value, sign or precision.
Thus MISRA-C:2012 requires the use of stronger typing, as enforced by its essential type model, which reduces the likelihood of these problems occurring.
Unfortunately many tools have not properly implemented the rules and the type model. In this case, your tool is incorrect, this is not a violation of essential type rules because ProgramStatus and FLS_PROG_SUCCESS are both the same essential type. In fact a similar example is shown in the standard itself, under the rule’s list of compliant examples:
enum enuma { A1, A2, A3 } ena;
ena = A1;
If your tool vendor disagrees you can post your question on the "official" MISRA forum to get the official answer and forward that to the vendor.

What does this colon do in an enum declaration?

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 .. };

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.