Go Down

Topic: Trivial questions (Read 1 time) previous topic - next topic

pYro_65



Sometimes the compiler cannot always guarantee a variable is a compile time constant, whereas an enum is by nature.


Can you explain that? I know that const-ness can be cast away or lost in some situations, but I would have thought that a const instance of an Enum type can lose its const-ness in exactly the same way that a const instance of an int type can.


I'll have a go.

I'm talking about an enum type, not an instantiated object of it. Any variable marked const ( including enum types ) can have the const cast away using 'const_cast<>()'

The values used to define an enums range must be compile time constants themselves, as enum type values are usable in templates.
Code: [Select]
#define LED_PIN 13

const char LED_PIN = 13;

enum{
 LED_PIN = 13
};

void setup( void ){
 pinMode( LED_PIN, OUTPUT );
}

All three of these are interchangeable, then main difference is the const char is a 'read-only object', the enum is a constant expression, and we all have hopefully heard of some compelling reasons why macros are not so great.

I prefer to keep large sets of enum values named, so I use a class based enum.

Code: [Select]
struct IO{
 enum{
   Led = 13,
   Btn = 12,
 };
};

void setup( void ){
 
 pinMode( IO::Led, OUTPUT );
 pinMode( IO::Btn, INPUT );
}

void loop( void ){

 if( digitalRead( IO::Btn ) ){

   digitalWrite( IO::Led, HIGH );

   while( digitalRead( IO::Btn ) );

   digitalWrite( IO::Led, LOW );
 }
}


And as you can see, there is no need to instantiate a variable of the enum type.
Also as a class based approach you can define methods/functions specific to that enum.

On a small side note: enums can be defined in macros, whereas you cannot define further #defines in a macro.

Go Up
 


Please enter a valid email to subscribe

Confirm your email address

We need to confirm your email address.
To complete the subscription, please click the link in the email we just sent you.

Thank you for subscribing!

Arduino
via Egeo 16
Torino, 10131
Italy