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 ca开发者_StackOverflow社区n have this variable named Var increment?)
You can just cast to int
and back, of course:
var = (Type) ((int) var + 1);
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.
精彩评论