一种情况下的多种情况
问题描述:
嗨!我需要在一个案例中使用多个条件。
这是我的代码:
Hi! I need to use multiple conditions in one case.
This is my code:
#define BLUE 0x00010000
#define GREEN 0x00000001
#define RED 0x00020000
DWORD Colors = BLUE | GREEN;
switch(Colors)
{
case BLUE | RED, BLUE | GREEN:
{
OutputDebugString("OK");
break;
}
}
如果我将颜色设置为 BLUE |绿色条件成功执行,我可以看到确定消息。
但如果我将颜色设置为蓝色| RED - 没有任何反应。
重要的是:不要移动 BLUE |红色和蓝色|绿色分开个案。
为什么不起作用?是否有可能实现它?
谢谢!
If I set Colors to BLUE | GREEN the condition executes successfully and I can see "OK" message.
But if I set Colors to BLUE | RED - there are nothing happens.
It is important: do not move BLUE | RED and BLUE | GREEN to separate cases.
why is it not working? And is it possible to implement it?
Thanks!
答
Acase
只能包含一个常量表达式。逗号没有给你两个不同的情况导致相同的代码,它正在评估两个表达式然后扔掉第一个。
参见:Comma Operator [ ^ ]案例
指定开关必须完全匹配,没有办法对匹配进行任何分析。我认为我肯定实现此目的的唯一方法是违反不分离它们的约束:
Acase
can contain only a single constant expression. The comma is not giving you two different cases that lead to the same code, it is evaluating both expressions and then throwing away the first one.
See: Comma Operator[^]
Thecase
specifies a value which the expression in theswitch
must exactly match, there's no way to perform any analysis to the matching.I thinkI'm sure the only way to accomplish this is to violate the constraint on not separating them:
switch(Colors)
{
case BLUE | RED:
case BLUE | GREEN:
{
OutputDebugString("OK");
break;
}
}
你在哪里找到这种语法?它总会评估到最合适的陈述。
http: //stackoverflow.com/questions/9358224/case-command-for-checking-two-values [ ^ ]
Do:
Where did you find that syntax? It will always evaluate to the right most statement.
http://stackoverflow.com/questions/9358224/case-command-for-checking-two-values[^]
Do:
DWORD Colors = BLUE | GREEN;
switch(Colors)
{
case BLUE | RED:
case BLUE | GREEN:
{
OutputDebugString("OK");
break;
}
}