I have got a enum
typedef enum State_t {
NOT_READY = 0,
NULL = 1,
READY = 2,
NOT_READY = 3,
WORK_READY = 4
} State_t;
If we assign
State_t state_t = -1;
Would it cause any issue?
I have got a enum
typedef enum State_t {
NOT_READY = 0,
NULL = 1,
READY = 2,
NOT_READY = 3,
WORK_READY = 4
} State_t;
If we assign
State_t state_t = -1;
Would it cause any issue?
It will not cause "memory corruption." It may however cause a surprising value to exist in the variable, either -1 if the enum type is signed or some huge value if it is unsigned. Enums are generally signed by default, but this is not guaranteed by the language standards.
The title of the question asks a very different question than does the body of the question. The title asks whether the assignment will cause memory corruption. The body asks whether it could cause any issue.
These are two very different questions. As several of the other answers have correctly noted, this assignment will not result in memory corruption. It can however cause "issues", particularly in a switch statement. The compiler is free to assume that the only values that an object of some enumerated type can take on are those listed in the enumeration.
#include <iostream>
enum abc {
a = 1,
b = 2,
c = 3
};
char to_letter (abc l)
{
switch (l) {
case a :
return 'a';
case b :
return 'b';
case c :
return 'c';
default :
return 'z';
}
}
int main ()
{
lower_case_letter x;
x = static_cast<abc>(-1);
std::cout << to_letter(x) << '\n';
}
In every implementation I've worked, this will print 'z'. That, however, relies on unspecified behavior. (That's not as bad as relying on undefined behavior, but it is a close second.) The compiler is free to assume that the only possible values that the argument to to_letter
takes on are the three values explicitly specified in the enum
.
No memory corruption. If it is unsigned one, you may see a very big value stored in variable.