Martijn Courteaux
Martijn Courteaux

Reputation: 68847

C++ / Java: Toggle boolean statement?

Is there a short way to toggle a boolean?

With integers we can do operations like this:

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

So is there also 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?

Upvotes: 6

Views: 2266

Answers (4)

Nemanja Trifunovic
Nemanja Trifunovic

Reputation: 24561

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

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

Then you use it like:

bool booleanWithAVeryLongName = true;      
toggle(booleanWithAVeryLongName); 

Upvotes: 6

lc.
lc.

Reputation: 116458

I think a better analogy would be that you're looking for the boolean equivalent of the unary operator ++, which I'm quite sure doesn't exist.

I never really thought about it, but I guess you could always XOR it with TRUE:

booleanWithAVeryLongName ^= TRUE;

Not sure it saves much and is a bit of a pain to read though.

Upvotes: 2

Uri
Uri

Reputation: 89729

Not exactly that, but in C/C++ there are operators for bitwise AND/ORs with assignment.

For logical ANDS/ORs between expressions - I don't think that there is.

However, in C you don't really have a bool type, just ints, so you could possibly use the integer operators to accomplish such shortcuts.

Upvotes: 0

Petar Minchev
Petar Minchev

Reputation: 47373

There is no such operator, but this is a little bit shorter: booleanWithAVeryLongName ^= true;

Upvotes: 25

Related Questions