14

I have a question about enum C.

I defined an enum in the following way:

typedef enum
{
    Hello1 = 1,
    Hello2 = 2,
    Hello3 = 3
}Hello

Hello hello;

int value = 3;  

then how to compare the value with the value in Hello?

for example:

if(value == Hello3)
{
}

or should I do it like the following:

if(value == Hello.Hello3)
{
}
alk
  • 69,737
  • 10
  • 105
  • 255

2 Answers2

31

This way is correct:

 if (value == Hello3)
 {
 }

enum constants are of type int.

Your second construct is invalid.

ouah
  • 142,963
  • 15
  • 272
  • 331
6

enum is not a structure and the member names are just names of the corresponding constants. These names defined in enum are not the data members of enum like in struct (as you are thinking).

So remember enum are used to define a list of named integer constants which we can do using #define also.

So here in your case:

if(value == Hello3)
{
}

This is the correct way to compare as it replaces Hello3 by the value 3 (which is nothing but int) at compile time.

For example you can do it also like this:

Hello hello=2;
if(hello == Hello2)
{
}
alk
  • 69,737
  • 10
  • 105
  • 255
Omkant
  • 9,018
  • 8
  • 39
  • 59