Reputation: 1
I want to use a particular macro depending on the value of variable. How can we do that in c++?
Example:
#define ONE 1
#define TWO 2
#define THREE 3
#define FOUR 4
int main()
{
int i = 0;
i = fun();
if (i == 1)
printf("%d\n", ONE);
else if(i == 2)
printf("%d\n", TWO);
else if(i == 3)
printf("%d\n", THREE);
else if(i == 4)
printf("%d\n", FOUR);
return 0;
}
How can I do this without using so many if else statements?
Upvotes: 0
Views: 64
Reputation: 218343
You may use switch:
switch(fun()) {
case 1: printf("%d\n", ONE); break;
case 2: printf("%d\n", TWO); break;
case 3: printf("%d\n", THREE); break;
case 4: printf("%d\n", FOUR); break;
default: break;
}
or array in your case:
const int ints[] = {ONE, TWO, THREE, FOUR};
const int i = foo();
if (1 <= i && i <= 4) {
printf("%d\n", ints[i - 1]);
}
For sparse values (for i
), a std::map
should replace the array.
Upvotes: 1