I’ve started learning C and have reached the point of enums. An enum is basically a preferred alternative to DEFINE / const int, correct?
What’s the difference between these two declarations?
#include <stdio.h>
// method 1
enum days {
Monday,
Tuesday
};
int main()
{
// method 1
enum days today;
enum days tomorrow;
today = Monday;
tomorrow = Tuesday;
if (today < tomorrow)
printf("yes\n");
// method 2
enum {Monday, Tuesday} days;
days = Tuesday;
printf("%d\n", days);
return 0;
}
An enumeration should be preferred over
#define/const intwhen you want to declare variables that can only take on values out of a limited range of related, mutually exclusive values. So the days of the week is a good example, but this would be a bad example:Going back to your code example; the first method declares a type called
enum days. You can use this type to declare as many variables as you like.The second method declares a single variable of type
enum { ... }. You cannot declare any other variables of that type.