Pages: 1 [2]   Go Down
Author Topic: Trivial questions  (Read 685 times)
0 Members and 1 Guest are viewing this topic.
North Queensland, Australia
Offline Offline
Edison Member
Karma: 52
Posts: 1778
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

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.
#define LED_PIN 13

const char LED_PIN = 13;

  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.

struct IO{
    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.

Pages: 1 [2]   Go Up
Jump to: