How do I find it? The forum search didn't bring up anything useful, mostly hits for posts that containe "enum" and the other terms in a totally unrelated context.
Using a tiny test I created for a different problem, found out that using enum uses more memory. Somewhere I read that enum is an int, is that true? If so, then it would make sense since int is 2 bytes versus char 1 byte. Is it possible to make the enum and uint8_t?
adilinden:
But what about enum? What is accomplished by using enum instead of multiple const?
const char BLUE = 0;
const char RED = 1;
const char GREEN = 2;
versus
enum colors {
BLUE,
RED,
GREEN
};
In the enum case, you don't have to say what the values should be -- although you can, if you want. With a const, you have to say the value. If you don't care what the values are, then enum may be more appropriate.
In the case of const, it is possible to take the address of the symbol. eg, it is possible to do this:
With an enum version of BLUE, you will get an error.
As with most things, there are 3 or more ways to skin any particular cat, and in many cases, no single right way, nor even a single way that is generally accepted as best.
As an old-school guy, I always use #define, and that is still a very commonly seen idiom for any constant requirements.
gardner:
As an old-school guy, I always use #define, and that is still a very commonly seen idiom for any constant requirements.
Well, to me a variable is just that, a container to hold value that is changed by the program. As such I would expect it to be stored in RAM. A #define to me is like a macro, something the compiler replaces with the value, something that is defined once and cannot be changed during program execution.
Personally I prefer #define. But then I am learning a lot and I am not adverse to doing things in a different way of it is beneficial.
I changed it to extern uint8_t state;. The result is 3366 bytes, so no difference in code size between using enum, const or define. I suppose it then comes down to preference, readability, etc...
It seems that const, enum, and define all do the same thing -- if the variable is unused, the compiler doesn't use it. Also, they take up the same amount of memory.
One advantage of const or #DEFINE over enum is that the value of the parameter can be overloaded to have some use. For example, I had a program with a state-tracking variable, and LEDs that changed to indicate state. I set it up like this:
void updateLEDstate()
{
// turn off all LEDs
digitalWrite(led1pin, LOW);
digitalWrite(led2pin, LOW);
digitalWrite(led3pin, LOW);
// turn on LED corresponding to current behavior state
digitalWrite(currentState, HIGH);
}
This avoids needing a switch(currentState) construct.