for enum cannot work

Why is this not working
1
2
3
4
5
6
7
8
9
10
11
12
13

enum L{
	j, k, l

};


int main(){

	for ( int i : L)		
	cout<< i<<"\n";

}

Last edited on
Because enums are not iterable.

This is as close as it gets, without using an intermediate compilation step:
1
2
3
4
5
6
7
8
9
10
11
12
enum Fruit{
    Apple = 0,
    Banana,
    Orange,
    Grape,
    Mango,
    COUNT,
};

//...
for (int i = Apple; i < COUNT; i++)
    std::cout << (Fruit)i << std::endl;
The output will not be "Apple", "Banana", etc. Actually, at the moment I can't remember if operator<<()ing an enum value to std::cout compiles without user-defined overloads.
That’s not how for loops work. You should try using a switch statement.

1
2
3
4
5
6
7
8
9
switch (myEnum)
{
case MyEnum::enum1:
    // ...
    break;
case MyEnum::enum2:
    // ...
    break;
}

If you needed to use a for loop, create a constrainer such as std::vector and store enum instances there.

1
2
3
4
5
6
7
std::vector<MyEnum> enums;
enums.emplace_back(MyEnum::enum1);
// ...
for (MyEnum myEnum : enums)
{
    // ...
}


Also, you should not use plain enums in C++. Use enum classes instead.

1
2
3
4
enum class MyEnum
{
    first, second, third
};
Last edited on
Topic archived. No new replies allowed.