Click here to Skip to main content
15,898,689 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi! I need to use multiple conditions in one case.
This is my code:

C++
#define BLUE           0x00010000
#define GREEN          0x00000001
#define RED            0x00020000


DWORD Colors = BLUE | GREEN;

	switch(Colors)
	{
		case BLUE | RED, BLUE | GREEN:
		{
		OutputDebugString("OK");
		break;
		}
	}


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!
Posted

A case 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[^]
The case specifies a value which the expression in the switch must exactly match, there's no way to perform any analysis to the matching.
I think I'm sure the only way to accomplish this is to violate the constraint on not separating them:
C++
switch(Colors)
{
    case BLUE | RED:
    case BLUE | GREEN:
    {
    OutputDebugString("OK");
    break;
    }
}
 
Share this answer
 
v2
Comments
Igor-84 20-Nov-15 17:59pm    
Explain me please, "not separating them" - is it violation?
Matt T Heffron 20-Nov-15 18:08pm    
In your original question you specified:
It is important: do not move BLUE | RED and BLUE | GREEN to separate cases.
This is the "constraint" to which I was referring.
The only way to get the behavior you seem to be trying to accomplish is to use separate cases which would "violate" your "constraint".
Igor-84 20-Nov-15 18:16pm    
Thanks!
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:

C++
DWORD Colors = BLUE | GREEN;
 
	switch(Colors)
	{
		case BLUE | RED:
               case BLUE | GREEN:
		{
		OutputDebugString("OK");
		break;
		}
	}
 
Share this answer
 
v2
Comments
Igor-84 20-Nov-15 17:55pm    
Thanks! I have translated a similar code from Delphi to C++. In Delphi it is permissible.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900