# Set Boolean Variable to opposite, eg if true, set to false, and vice versa.

This topic is 4527 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

## Recommended Posts

Hi, I am using C++. I have the following code
   if(m_bSelected==true)//toggle boolean variable
m_bSelected=false;
else
m_bSelected=true;


Is there some simpler way to make a boolean variable such as m_bSelected be set to the opposite of what it is set to (eg if true, then set to false, vice versa).

##### Share on other sites
mbSelected = !mbSelected

##### Share on other sites
I usually just do
m_bSelected = !m_bSelected;

##### Share on other sites
m_bSelected = !m_bSelected;

Edit: wow 3 posts in 8 seconds...

##### Share on other sites
bool b = true;

b = !b; //false
b = !b; //true

Edit: Wow, nice timing =)

##### Share on other sites
In case this isn't a joke, here:

m_bSelected = !m_bSelected;

##### Share on other sites
In the case that this *IS* a joke:

m_bSelected = m_bSelected ^^ true;m_bSelected = m_bSelected ? false : true;m_bSelected = (bool)((((int)m_bSelected)+1)&1);

##### Share on other sites
Quote:
 Original post by Sr_GuapoEdit: wow 3 posts in 8 seconds...

Yeah, somebody finally asked a question we all knew.

##### Share on other sites
Thanks everyone.

I just knew there would be a one line version of that code.

Thanks.

##### Share on other sites
Quote:
 Original post by TANSTAAFLIn the case that this *IS* a joke:m_bSelected = m_bSelected ^^ true;

Ummm, ^^ is not an operator. Or was that the joke?

1. 1
Rutin
36
2. 2
3. 3
4. 4
5. 5

• 12
• 14
• 9
• 9
• 14
• ### Forum Statistics

• Total Topics
633344
• Total Posts
3011436
• ### Who's Online (See full list)

There are no registered users currently online

×