Anuj Priyadarshi
Anuj Priyadarshi

Reputation: 349

Casting enum variable to enum type

I have encountered a code where enum variable is casted to enum type. I am unable to understand the use of such casting. For E. g.

typedef enum{x,y,z} en;

void main(){
  en const v;
  switch(v){
  case (en)y : {
    }
    break;
  case (en)x: {
    }
    break;
  default : {
    foo();
    }
    break;
  }
}

What is the use of casting x or y to enum type that is (en)x in case label?

Upvotes: 0

Views: 74

Answers (1)

Bathsheba
Bathsheba

Reputation: 234665

Such code is symptomatic of sheer paranoia, that's all. In fact, it's possibly harmful since in forcing a cast, you're hinting to the compiler that you know what you're doing so it may not warn you of an errant case label.

switching directly on an enum is perfectly valid, as enums are essentially integral types. You can safely drop the (en) casts.

Upvotes: 3

Related Questions