maddy
maddy

Reputation: 827

Enum values doubts?

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?)

Upvotes: 4

Views: 748

Answers (2)

Matthew T. Staebler
Matthew T. Staebler

Reputation: 4996

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.

Upvotes: 1

unwind
unwind

Reputation: 399803

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

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

Upvotes: 4

Related Questions