Mutually exclusive bitflags

How can you make bitflags mutually exclusive? I have a client/server program that sends files. The client and server are the same program, run in one of two modes. The user chooses which via the command-line. The two modes need to be mutually exclusive. I think the way to do that is to make one of the numbers not a power of two (so if a = 2 and b = 3 then a and b are mutually exclusive) but I'm not entirely sure. Plus, it doesn't work if the flags start at 1 since 1 and 2 are both powers of 2 (20 and 21). The other problem is that I use the bitflags variable for other command-line options and I don't want to affect them.

Currently I have something like this:
1
2
3
4
5
6
enum NSFlags {
	Client  = 1,
	Server  = 2,
	GUI     = 4,
	Default = Client | GUI,
};

I need Client and Server to be mutually exclusive but not affect GUI or any other flags I add later.
Last edited on
The easiest solution to your problem i can imagine is to use bitflags like this:

1
2
3
4
5
6
enum NSFlags {
	Client  = 0,
	Server  = 1,
	GUI     = 2,
	Default = Client | GUI,
};


Like this you'll use a single bit that indicates whether you want the program to be the client or server, and both isn't possible at the same time.

If you also want a mode where the program shall neither be client nor server (i.e. not establish a network connection in any way) you could simply add another flag like that:

1
2
3
4
5
6
7
enum NSFlags {
	Client  = 0,
	Server  = 1,
	NetworkMode = 2,
	GUI     = 4,
	Default = Client | NetworkMode | GUI,
};


Edit: This is similar to your approach using a=2 and b=3 as both ways use 2 bits to create mutally exclusive bitflags

Edit2: I just noticed it is identical to what you suggested, using a=2 and b=3, but i dont see why this shouldn't work.

Simplification of enum NSFlags:
1
2
3
4
5
6
7
enum NSFlags {
	Client  = 2,
	Server  = 3,
	//NetworkMode = 2,
	GUI     = 4,
	Default = Client | GUI,
};
Last edited on
That was how I thought it worked, thank you for confirming.
Topic archived. No new replies allowed.