tags:

views:

64

answers:

2

Is there any possible way to do any arithmetic operations 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 that this increment is not possible, but is there anyway by which we can have this variable named Var increment?)

+4  A: 

You can just cast to int and back, of course:

var = (Type) ((int) var + 1);
unwind
Thank you...I jst got it
maddy
A: 

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

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

You could replace the for loop that you are using with,

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

I do not condone such antics for enums in general, but for your particular case where the elements of the enum are integers, it works.

Matthew T. Staebler