Enum values ​​in doubt?

Is there any possible way to do arithmetic on enum values?

enum Type{Zero=0,One,Two,Three,Four,Five,Six,Seven,Eight,Nine}; main() { enum Type Var = Zero; for(int i=0;i<10;i++) { switch(Var) { case Zero: /*do something*/ case One: /*Do something*/ ..... } Var++; } } 

(I know this increment is not possible, but is there anyway that we can have this variable called Var increment?)

+4
source share
2 answers

You can simply translate to int and vice versa, of course:

 var = (Type) ((int) var + 1); 
+4
source

Yes, you can use enumeration types in arithmetic operations. Try the following code.

 if (Two + Two == Four) { printf("2 + 2 = 4\n"); } 

You can replace the for loop you are working with

 enum Type i; for(i=Zero; i<=Nine; i=(enum Type)(i + One)) { printf("%d\n", i); } 

I do not allow such tricks for enumerations in general, but for your specific case when the enumeration elements are integers, it works.

+1
source

Source: https://habr.com/ru/post/1307132/


All Articles