(C++) Simple Flag Toggle function

Post those lines of code you feel like sharing or find what you require for your project here; or simply use them as tutorials.
Post Reply
area51
Posts: 338
Joined: Thu Mar 18, 2004 10:20 pm
Location: UK
Contact:

(C++) Simple Flag Toggle function

Post by area51 »

This function simply toggles a boolean flag's state.

header file:

Code: Select all


...
private:
     
      bool m_bFlag;

public :

      void toggleFlag(){m_bFlag = !m_bFlag;}

As a general rule don't put logic in a header file, only the prototypes. But when it's that simple, who cares.
________
Self-Funded Health Care Forum
Last edited by area51 on Thu Feb 24, 2011 11:57 pm, edited 1 time in total.
jclins
Posts: 86
Joined: Thu Jan 01, 2004 10:29 pm
Location: Texas, USA

Post by jclins »

Nice!
Baal Cadar
Posts: 377
Joined: Fri Oct 28, 2005 10:28 am
Contact:

Post by Baal Cadar »

This code prints the line "Hello World!" to the standard output:

Code: Select all

std::cout << "Hello World!" << std::endl;
:roll:
Guest

Post by Guest »

I think you miss the meaning of the code snippets forum, posting code snippets of that quality makes no sense :P
area51
Posts: 338
Joined: Thu Mar 18, 2004 10:20 pm
Location: UK
Contact:

Post by area51 »

Sometimes you can learn from even the simplest of code samples
________
AMERICAN IDOL FORUM
Last edited by area51 on Thu Feb 24, 2011 11:57 pm, edited 1 time in total.
hybrid

Post by hybrid »

Yes, and sometimes it's just fun to read these code fragments. I suggest to make this thread sticky, I really love it :lol:
Warchief
Posts: 204
Joined: Tue Nov 22, 2005 10:58 am

Post by Warchief »

Improving:

Take a look at this code:

Code: Select all

typedef char byte; 
byte m_flags = 0;

void ToggleFlag(byte i)	{ m_flags ^= (1 << i); }

void EnableFlag(byte i)	{ m_flags |= (1 << i); }

void DisableFlag(byte i) { m_flags &= (!(1 << i)); }

bool IsEnabledFlag(byte i) { return(m_flags & (1 << i)) != 0; }
Note the last one includes an additional, not necessary, comparation !=0 (to avoid 'forcing int to bool warning').


I would like you to check this code (just paste and execute) tested on Windows:

Code: Select all

#include "time.h"

typedef char byte;
typedef unsigned long counter;
 
byte m_flags = 0;

int main()
{
	bool checkToggle = true;
	bool checkAsk    = true;

	counter max = ULONG_MAX, i1;	// Counting to
	time_t start, end, total;	// Time values
	bool flagX = false;
	int bit;

	if(checkToggle) {
		// Byte flag
		for(bit=0; bit<8; ++bit)  {

			time(&start);
			for(i1=0; i1<max; ++i1) m_flags ^= (1 << bit);
			time(&end);
			total = end - start;	
			printf("Toggle Flag (Bit %d): %u\n", bit, total);

		}

		// Bool flag
		time(&start);
		for(i1=0; i1<max; ++i1) flagX = !flagX;
		time(&end);
		total = end - start;
		printf("Toggle Flag (bool): %u\n", total);

                // Bool flag with Xor
		time(&start);
		for(i1=0; i1<max; ++i1) flagX = flagX ^ 1;
		time(&end);
		total = end - start;
		printf("Toggle Flag (bool): %u\n", total);
	}

	if(checkAsk) {	
		// Byte flag
		for(bit=0; bit<8; ++bit)  {

			time(&start);
			for(i1=0; i1<max; ++i1) if((m_flags & (1 << bit)) );
			time(&end);
			total = end - start;		
			printf("Ask Flag (Bit %d): %u\n", bit, total);
		}

		// Bool flag
		time(&start);
		for(i1=0; i1<max; ++i1) if(flagX);
		time(&end);
		total = end - start;
		printf("Ask flag (bool): %u\n", total);
	}

	return 0;
}
What i get from the execution is:
Toggle Flag (Bit 0): 20
Toggle Flag (Bit 1): 20
Toggle Flag (Bit 2): 21
Toggle Flag (Bit 3): 20
Toggle Flag (Bit 4): 21
Toggle Flag (Bit 5): 20
Toggle Flag (Bit 6): 21
Toggle Flag (Bit 7): 21
Toggle Flag (bool): 43
Toggle Flag (bool): 8 // Awesome
Ask Flag (Bit 0): 8
Ask Flag (Bit 1): 7
Ask Flag (Bit 2): 8
Ask Flag (Bit 3): 8
Ask Flag (Bit 4): 8
Ask Flag (Bit 5): 7
Ask Flag (Bit 6): 8
Ask Flag (Bit 7): 8
Ask flag (bool): 8
Note that your results may change due to differences in processor speed, hdd usage, mem usage, ....

Conclusion:
  • Using a byte (char) needs the same memory than a bool (yes, sizeof(bool) is 1 byte), but you can manage 8 different flags (opposite to the only one you can use with bool). Time for a toggle method is even reduced! Time needed for condition evaluation ['if' sentence] is almost the same. So if saving memory is a must, this can be the option
  • flag = flag ^ 1; uses Xor operation which is faster than negation of a bool. It is the fastest version of byte = byte ^ ( 1 << 0). If speed is a must, Xor is the best option
  • The funtions on the top call to m_flags, which is a global var or class atribute. You can use a define to allow calling with different flags or use a modified function to return the value.

    Code: Select all

    #define ToggleFlag(x) x = x^1 // or x^=1
    // use with ToggleFlag(bflag);
    
    // or
    
    bool GetToggleFlag(bool value) { return value ^ 1;  }
    // use with bflag = GetToggleFlag(bflag)
    

My mind is totally open for suggestions, tips, comments, flames or whatever you want. I think there are no errors in my comments above; but if you think so, let me know about it.
afecelis
Admin
Posts: 3075
Joined: Sun Feb 22, 2004 10:44 pm
Location: Colombia
Contact:

Post by afecelis »

you see? baby just got big! :wink:

I happen to like how the snippet forums are evolving.

keep it up guys!
@Area51: I also loved that short but TASTY code. :wink:
vitek
Bug Slayer
Posts: 3919
Joined: Mon Jan 16, 2006 10:52 am
Location: Corvallis, OR

Post by vitek »

DisableFlag is wrong... ! is a boolean negation operator. If any bit is set, the value becomes zero. ~ is the binary negation operator. It will flip every bit. It should be

Code: Select all

flag &= ~(1 << i);
The bool flag thing is great and all, but it should seriously be encapsulated, support error checking and arbitrary numbers of bits. For those who don't already know, the C++ stdlib already has a class does all of this... the vector<bool> specialization.

Travis
Spintz
Posts: 1688
Joined: Thu Nov 04, 2004 3:25 pm

Post by Spintz »

std::bitset
Image
vitek
Bug Slayer
Posts: 3919
Joined: Mon Jan 16, 2006 10:52 am
Location: Corvallis, OR

Post by vitek »

Yup. I came back to post that... Thanks spintz.
Last edited by vitek on Sun Feb 26, 2006 8:36 am, edited 1 time in total.
Warchief
Posts: 204
Joined: Tue Nov 22, 2005 10:58 am

Post by Warchief »

vitek wrote:DisableFlag is wrong... ! is a boolean negation operator. If any bit is set, the value becomes zero. ~ is the binary negation operator.
Totally right, my mistake.

About vector<bool> or bitset are also nice points. (My code is more from C than C++). I have never used any of them, but will give them a try.

The code snippet will be of use after all. :D
Eternl Knight
Posts: 313
Joined: Tue Nov 01, 2005 5:01 am

Post by Eternl Knight »

std::bitset or std::vector<bool> (which pretty much amount to the same thing) just go to show the benefits of STL integration :P
Post Reply