Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why assignment by Logical Operators ( &&= and ||= ) is missing in C/C++?

1) Why there is no assignment by logical operator like there is assignment by sum and difference?

bool a = true;
bool b = false;
a = a || b;
a ||= b; // syntax error!
a |= b;   // OK.

2) What is the meaning of applying bitwise operator on boolean variable? Is it the same as using logical operator?

like image 734
Sanich Avatar asked Apr 10 '16 07:04

Sanich


1 Answers

It's true that &&= and ||= are "missing" from C. I think one reason is that logical AND and OR in C perform short-circuiting, which would be a little strange in the abbreviated form. But don't use the bitwise assignment operators in their place. Instead, just write:

a = a && b;
c = c || d;

The bitwise operators will work if you have canonical true/false values (1 and 0). But if applied to non-canonical values, such as 5 and 2, you will get different results (5 && 2 is 1, but 5 & 2 is 0).

like image 134
Tom Karzes Avatar answered Sep 20 '22 15:09

Tom Karzes