0

Following is my test code

#include "test.h"
#include <iostream>

typedef enum{
    A = 0,
    B
 } testEnum;

int main()
{
    testEnum e = static_cast<testEnum>(3);
    printf("My enum Value : %d\n", (int)e);
    int stop = 0;
}

programs out is My enum Value : 3 Now in program i am type casting number 3 into enum and then printing it as int. My guess way this should give error or garbage value or 1 (as enum highest value). But out put is 3. Can somebody what are the rules and how it works. Thank you!

DigviJay Patil
  • 986
  • 14
  • 31

2 Answers2

2

n3376 5.2.9/10

A value of integral or enumeration type can be explicitly converted to an enumeration type. The value is unchanged if the original value is within the range of the enumeration values (7.2). Otherwise, the resulting value is unspecified (and might not be in that range).

ForEveR
  • 55,233
  • 2
  • 119
  • 133
1

Enum in an integral type (number). By type casting, you tell the compiler that you know the value is correct but there is no conversion occuring. You need to check the values/range yourself.

Btw. it actually gives a garbage value: 3

StenSoft
  • 9,369
  • 25
  • 30