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
  • 68,300
  • 10
  • 92
  • 234
  • 8
    I notice that you've been asking a lot of really basic questions on C lately on here on SO - maybe it's time to get hold of a decent introductory book on C ? You'll learn a lot faster that way rather than doing it iteratively via questions and answers here. – Paul R Nov 09 '12 at 09:02
  • 2
    May I suggest http://en.wikipedia.org/wiki/The_C_Programming_Language, by the creators of the language? It is not a big book (as C is not a big language) and the examples are fun to work through. – Hans Then Nov 09 '12 at 09:06
  • 1
    ok, I think you are right, I do need to read a c language book, any book you recommoned? –  Nov 09 '12 at 10:21
  • There's a very good list of recommended books right here: http://stackoverflow.com/questions/562303/the-definitive-c-book-guide-and-list – Paul R Nov 09 '12 at 15:42

2 Answers2

29

This way is correct:

 if (value == Hello3)
 {
 }

enum constants are of type int.

Your second construct is invalid.

ouah
  • 138,975
  • 15
  • 262
  • 325
5

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
  • 68,300
  • 10
  • 92
  • 234
Omkant
  • 8,730
  • 7
  • 37
  • 59