简体   繁体   English

根据变量的值确定宏

[英]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++? 我们如何在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? 如何在不使用太多if语句的情况下做到这一点?

You may use switch: 您可以使用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. 对于稀疏值(对于i ),应使用std::map替换数组。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 宏来确定变量是否是指针 - Macro to decide whether variable is pointer or not 变量+值宏扩展 - variable + value macro expansion 在取消定义之前,将宏变量的值使用/复制到宏函数中/将其复制到宏函数中:是否可能? - Using/Copying the value of a macro variable in/to a macro function before undefining it: is it possible? 在宏函数C ++中设置宏变量值 - Setting macro-variable-value in macro-function C++ 如何使用可变数量的参数获取Macro的值? - How to get the value of Macro with variable number of arguments? 为什么在给变量分配超出范围的值时由编译器决定要分配什么值 - why it is up to the compiler to decide what value to assign when assigning an out-of-range value to a variable 根据宏定义具有多种类型的一个变量的可能性 - Possibility of defining one variable with multiple types based on a macro 是否可以基于宏或变量有条件地编译/运行代码? - Is it possible to conditionally compile / run code based on a macro OR a variable? 有没有办法根据是否定义将变量宏转换为0或1? - Is there any way to convert a variable macro into 0 or 1 based on whether it is defined? 宏或 c++ 模板更改 struct 或 class 中的 const 变量值 - Macro or c++ template to change const variable value in struct or class
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM