C ++ / Java: Toggle Boolean operator?

Is there a short way to switch logical?

With integers we can do the following operations:

int i = 4; i *= 4; // equals 16 /* Which is equivalent to */ i = i * 4; 

So, is there something for booleans (like the *= operator for ints)?

In C ++:

 bool booleanWithAVeryLongName = true; booleanWithAVeryLongName = !booleanWithAVeryLongName; // Can it shorter? booleanWithAVeryLongName !=; // Or something? 

In Java:

 boolean booleanWithAVeryLongName = true; booleanWithAVeryLongName = !booleanWithAVeryLongName; // Can it shorter? booleanWithAVeryLongName !=; // Or something? 
+6
java c ++ boolean toggle
source share
4 answers

There is no such statement, but it is a little shorter: booleanWithAVeryLongName ^= true;

+25
source share

How about a simple function (in C ++):

 void toggle (bool& value) {value = !value;} 

Then you use it like:

 bool booleanWithAVeryLongName = true; toggle(booleanWithAVeryLongName); 
+6
source share

I think the best analogy would be that you are looking for the logical equivalent of a unary operator ++ , which I am sure does not exist.

I never thought about this, but I think you could always XOR with TRUE:

 booleanWithAVeryLongName ^= TRUE; 

I'm not sure that he saves a lot and reads a little pain.

+2
source share

Not quite so, but in C / C ++ there are operators for bitwise AND / OR with purpose.

For logical ANDS / OR between expressions - I do not think that is.

However, in C, you really don't have the bool type, just ints, so you can use whole operators to execute such keyboard shortcuts.

0
source share

All Articles