# How do flags work?

• 07-21-2005
vexon
How do flags work?
I wonder this... how to flags work how do you intercept them and how to use them in your own functions?

Just a simple question i guess :p
• 07-21-2005
When I think of flags I think of variables that can be used to alter flow at certain juctures based on their current value. They are usually used as conditionals in if/else statements or loops within a function. In the example below, parenthesisPresent is what I call a flag
Code:

```void processEquation(string & eq) {   bool parenthesisPresent = evaluateForParenthisis(eq);   if(parenthesisPresent)   expandParenthesis(eq);   else   solveEquation(eq); }```
• 07-21-2005
dwks
Or you can use flags to pass information between functions.
Code:

```void func(int &i); int main() {     int quit = 0;     while(!quit) func(&quit);     return 0; } void func(int &i) {     i = 1; }```
• 07-21-2005
DougDbug
A flag is a 2-state variable. (Like the red flag on a mail box... its either up, or down.)

It is usually simply an integer with a value of 1 or 0, which represents a "state" or "condition" such as off or on, true or false, yes or no, etc. You might have a flag called LOOP, and then use something like while(LOOP = 1), or more commonly while(LOOP).

Some typical flag variable names:
Loop
Exit
Quit
Stop
Run
Error
Pass
Fail
Full
Empty
LED_on
Switch_on

Now, if you're not up-to-speed on you binary, this will be confusing... The Windows API uses lots of flags that are integer values which represent "bit-weights" or "bit positions". They have values that can be represented by one bit in a binary number... 1, 2, 4, 8, 16. This way, a single 32-bit integer can contain 32 different flags. They are usually "ored" together to define set of related conditions. You normally use these WinAPI flags without knowing their actual integer value or bit-position... You simply "or" the true flags together as needed.
• 07-21-2005
Darryl
I think the OP means bit flags for ex byte Flags = Foo | Bar;

Bitflags extends the idea of a flag variable mention in the other post, but by using only 1 bit of a variable to represent each flag, many can be combined into a single variable to increase efficency.

It basically works like this. You take any regular variable and assign meaning to each of its bits, individual flag are created to represent 1 bit of the variable, by combining them you can set various bits of the variable. In my instance I used an 8 bit byte (char) variable.

What ever function that uses the flags can test the various bits of the storage variable to interpret the correct setting. Take my example above foo might be 00000001 and bar = 00000010. Or'ing them together like I did will produce 00000011;

Now I can test the Flags variable like:
If (Flags & Foo) to see if Foo bit is set and if (Flags & Bar) to see if Bar bit is set.