Stefan Stojkovski
Stefan Stojkovski

Reputation: 488

Enumeration in C

enum {YES=1,No=0};
int main()
{
    int i;
    i=YES;
    printf("%d",i);
}

works well.

enum B{YES=1,NO=0};
int main()
{
    enum B i;
    i=YES;
    printf("%d", i);
}

also works well.

typedef enum {YES=1,NO=0} Boo;
int main()
{
    Boo i;
    i=YES;
    printf("%d", i);
}

works too. Is there any difference? When is one of them preferred over another?

Upvotes: 1

Views: 179

Answers (3)

ach
ach

Reputation: 2373

Theoretically, there's a little catch in your 2nd and 3rd examples.

Unlike C++, standard C merely says that each enumerated type shall be compatible with an integer type. The choice of type is implementation-defined.

Therefore it is theoretically possible (though, of course, barely sensible and probable) that an implementation chooses an integer type which has a higher rank than that of int.

In such case, the %d format specifier may not correspond to the promoted type of i, which means undefined behavior.

Upvotes: 1

Vaughn Cato
Vaughn Cato

Reputation: 64308

In C, there is very little difference been a variable with an enum type and a regular int. C allows implicit conversion from an enum value to an int as well as implicit conversion from an int to an enum value, so they are practically interchangeable. The only practical difference that I know of is that using the enum type will more clearly express your intent that the values should only be one of the named values of the enumeration.

Note that this is in contrast to C++, where enum values can be implicitly converted to int, but not the other way around.

Upvotes: 3

Jacob Pollack
Jacob Pollack

Reputation: 3761

The difference between your first and second (and third) example is that you are defining i as two separate data types. One being an int and the other being an enum B.

There is no difference between the second and third example. Recall that the purpose of typedef is to assign different names to data types (and also declaring opaque structures... don't get on me about that).

Upvotes: 0

Related Questions