简体   繁体   中英

Decide macro based on the value of variable

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM