2

I have problem trying to make for each loop in C++. I'm not certain is this is possible in C++ if it is I still dont know to make it.

I have one simple problem written in pascal that does finding of the day in year when it is a friday 13 or saturday 25 no metter which day.

In pascal I have code like this:

{First I declare types}
type
    months = (January, February, March, April, May, June, July, August, September, October, November, December);
...
{Then I declare variable for months}
var
    m: mesec;
...
{Then I can declare for loop that will loop over months}
for m:= januar to december do
...

The similar way of doing a for each loop over enumerations is possible in python too. My question is:

Is there any way of doing for or even while loop over enumerations in C++?

I know this may seem as a beginers question but I tried on few different ways to do it doesnt work. Doesnt compile.

3

2 Answers 2

6

You could do following in c++ provided the enum values are consecutive

enum Months
  {
  January,
  February,
  // etc...
  December,
  Last
  };

for (int month = January; month != Last; ++month)
  {
  // do stuff
  }
Sign up to request clarification or add additional context in comments.

3 Comments

But only if enums have consecutive values.
This stops right before December which is incorrect. Generally another enum value is added last called NumMonths and you use that.
Yes enum values are consecutive
4

No, you can't do this directly in C++. There are a few workarounds, though.

  • If the values of the enum are increased by 1 (i.e. have consecutive values, as they do by default, in case you don't explicitly set their values), you can use them as normal ints, and increase the cycle variable by 1 each time until it equals the last enum's value. This is described in this SO question.
  • If the values are not increasing by 1 (e.g. enum E {FIRST = 5, SECOND = 10}, it becomes more tricky. You could make an array holding all possible values and use it (that's a crappy solution, but it works):

    enum E
    {
        FIVE = 5,
        TEN = 10,
        THREE = 3
    };
    E arr[3] = {FIVE,TEN,THREE};
    E iterator;
    for( int i = 0; i < 3; i++ )
    {
        iterator = arr[i];
        //do something with it
    }
    

1 Comment

One benefit of this solution is the conciseness of ranged for: for( E val : arr ). Depending on your use case, you might benefit from having multiple subsets/orderings of the enum: E oddValues[] = { THREE, FIVE }; for( E val : oddValues ) ...

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.