# C Switch Statement Question (advanced)



## ricer333 (Sep 17, 2004)

Ok,
I will try this (testing) but wanted to know if anyone here knows the answer first.

When using a Switch statement, the cases are supposed to be constant. If I have a 1 byte (8 bit) variable that can have certain bits on or off, can I check by doing an Bit wise OR operation in the case?

EX:

```
Ip_u8 A = 56
switch (A)
{
  case 8:
    do this;
    break;
  case 48:
    do that;
   break;
  case 48 | 8:
    do whatever;
    break;
  default:
    break;
}
```
will the last case evaluate 48|8 then check what is passed in? it compiles just fine, and I will test, again, I don't know too many SW people that have done this and most of the examples do go to this depth.

What are you thoughts?


----------



## shuuhen (Sep 4, 2004)

I'd expect it to work, since 48|8 is a constant. The compiler should translate that to a single number for the switch statement.

Here's a small portion of what gcc -S spits out (assembly) on an AMD64 machine with a 64-bit install of Gentoo Linux:

```
movb  $56, -1(%rbp)
  movsbl  -1(%rbp),%eax
  movl  %eax, -20(%rbp)
  cmpl  $48, -20(%rbp)
  je  .L4
  [B]cmpl  $56, -20(%rbp)[/B]
  je  .L5
  cmpl  $8, -20(%rbp)
  je  .L3
  jmp .L2
```
The cmpl lines are just comparing a number to your variable (in this case it's at *-20(%rbp)* ). The *je* just sends it to where it runs the code you put in the specific case. The bold line is the one for 48|8. As far as I know this translation should always happen.

I'd expect bitwise operators with constant operands to be fine for the cases. Arithmetic operators with constant operands would probably work too.

Logical operations however, should NOT be used in the cases since logical operations evaluate to true (1) or false (0) possibly giving multiple 'case 1' or 'case 0' blocks.

If the bits are flags, why not specify them in hex? I'm not sure if I'm overlooking something (I haven't really specified the constants the way you want to).


----------



## ricer333 (Sep 17, 2004)

I have actually #defined the 48 and 8 to 'readable' constants (ex: #define BITS_OF_48_SIZE 48) that's why I'm not using hex. I could do that, but I already have these defined in another portion of the code, so just wanted to re-use for readability sake. 

Thank you for the response on this. When i get around to testing it, I will let you know. I expected that it would work based off of your description as well, but it's always good to get some feedback before going too much further.


----------

