# Examining flags when passed to a function?

• 02-01-2003
DominicTrix
Examining flags when passed to a function?
The syntax of my question is likely to be totally incorrect! This is what I meant:

When a function recieves a single variable that contains a set of flags seperated by the bitwise operator, how does it read those values and how are those values defined? i.e. I would like to write my own function that will take a set of flags as an argument.

e.g.
// Declaration
int Function(DWORD flags);

// Usage
i = Function(FLAG_X | FLAG_Y | FLAG_Z);

// Function Code:
?????????!

Hope this makes sense, and thanks in advance

dt
• 02-01-2003
kuphryn
Here is one solution.

Code:

```enum TypeX {tX1 = 0x0001, tX2 = 0x02,  tX3 = 0x0003} void DetermineType(const int nType) {          for(int type = tX1; type <= tX3; type = (type << 1))   {       if (nType & type)         // Type match.  Do something.   } }```
Kuphryn
• 02-01-2003
Sang-drax
Umm kuphryn, you cannot have 3 as a flag.
A flag must be a single bit, therefore valid flags are powers of 2.
1
2
4
8
16
32
... and so on.
• 02-01-2003
Sebastiani
let's say you want to use a 32 bit (4 byte ) integer to hold some flags. This just means to lay out the integer in binary format and and use each individual bit as an on/off, true/false, or similar binary flag.

00000000 00000000 00000000 00000000

Above is an integer with all bits 'cleared'.

01000000 00000000 00000000 00000000

Now we have set the second bit. To set a bit, we can | (OR) it to the number. We can do this in two ways. First, we can choose the zero-based index of the bit:

#define TRUE 1
int offset = 1; // second bit position

flag |= (TRUE << offset);

Would result in the second bit being set.

Second, you can simply use an integer value:

int value = 2;

flag |= value;

To determine if a bit is set:

if(flag & (TRUE << offset))
// then bit is set

or:

if(flag & value)
// then bit is set

To clear a bit & it with it's bit complement (~):

flag &= ~(TRUE << offset);

or:

flag &= ~value;

Hope that helps.
• 02-01-2003
kuphryn
Correct. Modify the enum accordingly.

Kuphryn
• 02-01-2003
DominicTrix
Brilliant, thanks guys, I think I get it now :-)

dt