Really tough array question!

Declare an array of floating point elements called week that can be referenced by using any day of the week as a subscript. Assume Sunday is the first subscript.

I have asked others this before and was told it was impossible. This is the first array I will have ever made and the question is straight out of my textbook. How could this be impossible? Any help is appreciated.
1
2
3
4
5
6
7
8
9
10
11
enum { Sunday, Monday,  Tuesday, Wednesday, Thursday, Friday, Saturday, DaysOfWeek = Saturday };

float array[DaysOfWeek];

array[Sunday] = 0.0;
array[Monday] = 1.1;
array[Tuesday] = 2.2;
array[Wednesday] = 3.3;
array[Thursday] = 4.4;
array[Friday] = 5.5;
array[Saturday] = 6.6;
Thanks!
Well, that's not good. DaysofWeek in that code is 6, and you write to 7 elements.

If the "= Saturday" is left off, it would be fine.
Last edited on
I have asked others this before and was told it was impossible


Really?

The code posted is fine.

You better learn hoe enums work though. Hint- they are actually read as integral types.

Moscow could have easily done this : enum { Sunday = 5, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, DaysOfWeek = Saturday };

Then, Saturday would = 11.
I made a mistake. Shall be

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

instead of

enum { Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, DaysOfWeek = Saturday };


I would remove DaysOfWeek from the enum as it is not a day of the week and it's therefore a category error to include it (in the enum).

I would use Day(s)OfWeek as the name of the enum. In that case you can use it to declare functions which can only take valid days.

1
2
3
enum DayOfWeek { Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday };

unsigned int GetCplusplusDailyPostCount(DayOfWeek day);


I have seen values added to enums for sizing reason before, but I dislike it for the reason I gave above. It breaks the "encapsulation" of the enum (that all members are valid values of the enum).

You could do something like the following instead?

1
2
3
enum DayOfWeek { Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday };

enum { DaysPerWeek = Saturday + 1 };


Or even just define DaysPerWeek to be 7, as it's a well-known value.
Last edited on
Topic archived. No new replies allowed.