icp/oer/courses/c-basics/sections/12-struct_enum/01-enums/program.c

96 lines
1.7 KiB
C

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
enum Day {
MONDAY,
TUESDAY,
WEDNESDAY,
THURSDAY,
FRIDAY,
SATURDAY,
SUNDAY
};
int DayTill(enum Day Current, enum Day Other)
{
return 0;
}
// Unfortunatly there is no easy way to print out enums as text,
// because internaly they are just numbers.
char *EnumToString(char *Dest, enum Day WeekDay)
{
// When we get to memory allocation you could do this without the destination buffer
switch(WeekDay)
{
case MONDAY:
{
strcpy(Dest,"monday");
}break;
case TUESDAY:
{
strcpy(Dest,"tuesday");
}break;
case WEDNESDAY:
{
strcpy(Dest,"wednesday");
}break;
case THURSDAY:
{
strcpy(Dest,"thursday");
}break;
case FRIDAY:
{
strcpy(Dest,"friday");
}break;
case SATURDAY:
{
strcpy(Dest,"saturday");
}break;
case SUNDAY:
{
strcpy(Dest,"sunday");
}break;
}
return Dest;
}
int main(int argc, const char *argv[])
{
// We can now assign variables one of our enums options.
enum Day current_day = MONDAY;
// To shorten the syntax we can also do a typedefinition:
typedef enum Day DayType;
// Now we just need to write:
DayType x = TUESDAY;
// Each of the enums options has an associated value so we can do:
if (x > current_day) {
printf("Tuesday is larger %d.\n", x);
}
char Buffer[32],Buffer2[32];
printf("Today is %s. %d days until next %s", EnumToString(Buffer, atoi(argv[1])), DayTill(atoi(argv[1]), atoi(argv[2])), EnumToString(Buffer2, atoi(argv[2])));
}
// If you want the values to be different, you can set them explicitly
enum Months {
JANUARY = 10,
FEBRUARY = 0,
MARCH = 33,
APRIL = 99,
MAY = 6,
JUNE = 42,
JULY = 27,
AUGUST = 3,
SEPTEMBER = 1,
OCTOBER = 4,
NOVEMBER,
DECEMBER = 5,
};