Can the following code be optimized any further (ie can it be turned into a one-line expression), through some bit-wise operation or something else?
if(A_BOOL_VARIABLE)
return (A == B);
else
return (A != B);
Note: A and B are not bool
type here.
return A_BOOL_VARIABLE == (A == B);
Truth table:
A_BOOL_VARIABLE (A == B) Result
T T T
T F F
F T F
F F T
Which is the same as your original if..else
.
Not bitwise, but a simple boolean XOR:
return A_BOOL_VARIABLE ^ (A!=B);
Here I suppose that A==B = !(A!=B)
.
Renaming your A_BOOL_VARIABLE
to C
for the sake of brevity, the truth table is:
C A B Result
0 0 0 0 \
0 0 1 1 | == A ^ B (C=0)
0 1 0 1 |
0 1 1 0 /
1 0 0 1 \
1 0 1 0 | == ! (A ^ B) (C=1)
1 1 0 0 |
1 1 1 1 /
So the final expression could be: A ^ B ^ C
where ^
is exclusive or.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.