• Advertisement
Sign in to follow this  

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

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

If you intended to correct an error in the post then please contact us.

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 this post


Link to post
Share on other sites
Advertisement
Guest Anonymous Poster
mbSelected = !mbSelected


Share this post


Link to post
Share on other sites
bool b = true;

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

Edit: Wow, nice timing =)

Share this post


Link to post
Share on other sites
In case this isn't a joke, here:


m_bSelected = !m_bSelected;

Share this post


Link to post
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 this post


Link to post
Share on other sites
Quote:
Original post by Sr_Guapo
Edit: wow 3 posts in 8 seconds...


Yeah, somebody finally asked a question we all knew.

Share this post


Link to post
Share on other sites
Thanks everyone.

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

Thanks.

Share this post


Link to post
Share on other sites
Quote:
Original post by TANSTAAFL
In the case that this *IS* a joke:

m_bSelected = m_bSelected ^^ true;

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

Share this post


Link to post
Share on other sites
Guest Anonymous Poster
m_bSelected = 1 - m_bSelected;

Share this post


Link to post
Share on other sites
convert.cpp

void __export convert_bool(bool *b)
{
switch(*b)
{
case true : *b=false; break;
case false: *b=true; break;

default: throw error();
}
}

int WINAPI DllEntryPoint(HINSTANCE,DWORD,LPVOID)
{
return 1;
}



Compile with BCC32 -WD convert.cpp.
Place resulting file in Windows->System32 folder.

main.cpp

#include <windows.h>

int main(int,const char **av)
{
HMODULE Hm=LoadLibrary("convert.dll");
if(Hm==NULL) throw error();

void(*f)(bool*)=(void(*)(bool*))GetProcAddress("_convert_bool");
if(f==NULL) throw error();

bool b=true;
f(&b);

FreeLibray(Hm);
return 0;
}




[Edited by - EasilyConfused on June 26, 2006 6:03:36 AM]

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement