10

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?

1

2 Answers 2

9

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).

Sign up to request clarification or add additional context in comments.

8 Comments

Please can you explain what 'short-circuiting' is?
Is bool type in C always canonical?
Short-circuiting for && and || means that the second operand is only evaluated if it is needed to determine the result. For example, if you have 0 && x, then x is not evaluated because you already know the answer is 0. Similarly, if you have 1 || y, then y is not evaluated because you already know the answer is 1. This is significant if the second operand is slow to evaluate (e.g., a function call), or has side effects.
As to whether bool types in C are always canonical, originally there was no bool type in C. Later versions of C introduced a bool type, and in C99 stronger support was introduced, but since bool variables are at least 1 byte in size, it is always possible to "force" non-canonical values into them through unions or pointer casting.
I did some research and it is not only a syntax difference. Assignment by operator correspond to a clearly different machine instruction and addressing mode. Read more HERE. But I still didn't find a good answer why &&= and ||= are "missing" from C. Knowing the information above, is it now more clear to you why are they missing or irrelevant?
|
2

a |= b means the same as a = (a | b), except that the address of a is evaluated only once. Then you look up the rules for promotion, and for assignment to bool.

1 Comment

Can you use bitwise operators on booleans?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.