Hi All,
Can anybody explain why the code below does not
work?
enum State {NONE, OFF, ON, RUN, STOP};
int StateArr[5];
State S;
for (S = NONE; S<=STOP; S++)
StateArr[S] = 10;
How can I fix the code?
Thanx
Hi All,
Can anybody explain why the code below does not
work?
enum State {NONE, OFF, ON, RUN, STOP};
int StateArr[5];
State S;
for (S = NONE; S<=STOP; S++)
StateArr[S] = 10;
How can I fix the code?
Thanx
Well, as far as I know the enum command sets up a number of constants with integer values. Thus, when you set up your for loop, you are trying to increment a constant; you might as well say "2++". Try the following:
[code]
enum State {NONE, OFF, ON, RUN, STOP};
int StateArr[ 5 ];
for (int i = NONE; i <= STOP; i++)
StateArr[ i ] = 10;
Claus Hetzer
Compiler: Borland 5.5 (on Windows)
Solaris CC (on Unix)
Known Languages: C++, MATLAB, Perl, Java
Originally posted by geophyzzer
Well, as far as I know the enum command sets up a number of constants with integer values. Thus, when you set up your for loop, you are trying to increment a constant; you might as well say "2++". Try the following:
[code]
enum State {NONE, OFF, ON, RUN, STOP};
int StateArr[ 5 ];
for (int i = NONE; i <= STOP; i++)
StateArr[ i ] = 10;
What do you mean?
Since S is a variable of State type? So S is
a constant??? Are you sure about this??
This is perfectly work in C, but not in C++ andCode:State S; for (S = NONE; S<= STOP; S++) StateArr[S] = 10;
I don't know why it has compile error.
DV007
In C++, you are not allowed to increment enums. In C, you are allowed to do so.
When all else fails, read the instructions.
If you're posting code, use code tags: [code] /* insert code here */ [/code]
>In C++, you are not allowed to increment enums.
Well, you can...but it gets ugly. I think there was a thread I answered about this a while back with reasons, a workaround, and alternatives.
-Prelude
My best code is written with the delete key.
If I may, (taken from The C++ Programming Language; Bjarne Stroustrup):
(Very likely the explanation, in part, that Prelude had presented in the earlier post she refers to.)Code:enum Day { sun, mon, tue, wed, thu, fri, sat }; Day& operator++ (Day& d) { return d = (sat==d) ? sun : Day(d+1); }
Note that, if the operator function is not a member, at least one argument must be passed to the operator function.
Interestingly, the operator function presented would seem to imply that enum's can, be incremented, i.e. Day(d+1), albeit with a limitation. The compiler-recognized value cannot be incremented for a specific member, but we can refer to another member of the enumeration by adding (subtracting?) a constant value from it.
Or, is this a misinterpretation on my part? (If I had a quarter...)
-Skipper
"When the only tool you own is a hammer, every problem begins to resemble a nail." Abraham Maslow