Switch statement in C question

if a switch case is given as
mask=0x01
switch (Buffer[2] & mask)
{
case 1:
---
if
else

case 2:
------
if
else

default:

}

I am doing unit testing in order to get 100% coverage and also test one ureq I need to enter default but I am not able to understand what switch (Buffer[2] & mask) means i.e what exactly the (Buffer[2] & mask) describe and & is used for what
The & operator does at bit-by-bit AND operation on the arguments. For example, if X is 12 (1010 in binary) and Y is 7 (0111 in binary) then X&Y is 2 (0010 in binary). To see why, notice that the 2nd bit from the right is the only one that is 1 in both X and Y.

Regarding your code, if mask=0x01 then mask & anything must be either 0 or 1. So in your switch statement, the program will execute the case 1 code if Buffer[2]&mask is 1, and the default case if Buffer[2]&mask is 0. The code for case 2 cannot be reached (assuming there is a break statement above it) and an optimizing compiler will probably remove it from the generated code.
Hi,
(Buffer[2] & mask)

It is an (and) (&) bit operation. It makes sure that the result from the operation does not exceed the value of (mask)

For example, if (Buffer[2]) is 19 and (mask) is 10. (Buffer[2]) is greater than (mask) so during the operation the value will be truncated. And the result of the operation is 2.

More info :
http://www.cplusplus.com/doc/boolean/
Last edited on
Does it help you? :)
Topic archived. No new replies allowed.