I'm still new to Arduino and coding in general. I have been going through lots of tutorials and other peoples projects/code and came across this snippet of code.
enum operatingState { OFF = 0, SETP, RUN, TUNE_P, TUNE_I, TUNE_D, AUTO};
operatingState opState = OFF;
Is this just an Array with out the [ ]?
Would someone be able to explain also why OFF=0 and the next line operatingState opState = OFF;
Thanks very much
The 'enum' are similar to integers or defines with incremental numbers.
Sometimes a state machine uses defines like this:
#define OFF 0
#define SETP 1
#define RUN 2
#define TUNE_P 3
#define TUNE_I 4
#define TUNE_D 5
#define AUTO 6
int opState = OFF;
But a 'enum' would be better:
enum operatingState { OFF = 0, SETP, RUN, TUNE_P, TUNE_I, TUNE_D, AUTO };
operatingState opState = OFF;
The big advantage is that the variable 'opState' is an integer of the type 'operatingState'.
The disadvantage is that when an extra element is added in between the others, the remaining elements do get a higher number. If those numbers are used in other places, everthing has to be updated for the new set of elements.
So if it is an array why don't they need to put the [ ] to say the size of the element? like this.
enum operatingState[]{ OFF = 0, SETP, RUN, TUNE_P, TUNE_I, TUNE_D, AUTO};
and so making OFF=0. since its enum (is like saying int) its like saying
int OFF=0 \\so now OFF stores a value of 0
Is this correct?
It is not an array, it is a enumerator.
An array has real elements that occupy a memory location.
An enumerator does not use a memory location. In your example, only the 'opState' is an integer with a memory location, and the 'OFF', 'SETP', and so on are defines.
Therefor it is not : int OFF = 0 ;
But it is : #define OFF 0
I admit that the use of 'enum' is very close to an array with values. The 'enum' has its own use and can be very handy. For me, there has been never any confusion when to use a 'enum' and when to use an array.
Koepel:
It is not an array, it is a enumerator.
"Enumeration". There is a difference.