2

If I want to implement the following code, would enums be appropriate? I've looked up a few questions on enums, but I'm still a bit unsure.

if (dayOfWeek == Monday)
{
    // Do something
}
else if (dayOfWeek == Tuesday || dayOfWeek == Wednesday)
{
    // Do something else
}

If this seems right, how would I go about initialising the enum? Would it go in the header or implementation file?

achiral
  • 601
  • 2
  • 11
  • 24

2 Answers2

7

If I want to implement the following code, would enums be appropriate?

Without getting too detailed about alternatives -- Yes.

how would I go about initialising the enum?

I typically declare an enum in C like so:

typedef enum MONDayOfWeek {
  MONDayOfWeek_Undefined = 0,
  MONDayOfWeek_Monday,
  MONDayOfWeek_Tuesday,
  MONDayOfWeek_Wednesday,
  MONDayOfWeek_Thursday,
  MONDayOfWeek_Friday,
  MONDayOfWeek_Saturday,
  MONDayOfWeek_Sunday
} MONDayOfWeek;

// in use:
MONDayOfWeek day = MONDayOfWeek_Monday;

MON would be your library or organization's prefix. DayOfWeek would be the enum name within the library, then the values are appended.

Although it's wordy, you tend to avoid collisions quite well.

Would it go in the header or implementation file?

In the header, if you want it to be used by multiple files, else in the implementation file.

justin
  • 104,054
  • 14
  • 179
  • 226
2

Yes this would be great for enums, check out this SO post to see the construction of an enum:

What is a typedef enum in Objective-C?

typedef enum {
    Monday,
    Tuesday,
    Wednesday,
    Thursday,
    Friday,
    Saturday,
    Sunday
} DayOfTheWeek;

Also, you can decide whether or not to place the enum implementation in the class you are working in or a header file.

Community
  • 1
  • 1
5StringRyan
  • 3,604
  • 5
  • 46
  • 69