Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting && (logical and) operator into || (logical or) operator

Tags:

c

bool a, b;

A)
if (a && b)
    return true;
else
    return false;

B)
if (!a || !b)
    return false;
else
    return true;

I am little bit confused. Are A & B equivalent??

like image 674
user966379 Avatar asked Dec 04 '25 12:12

user966379


2 Answers

Yes, they are equivalent, because of De Morgan's laws:

!(a && b) == !a || !b

hence

 (a && b) == !(!a || !b)

However, at any decent company, one would get fired quickly if one wrote code like this.

if (<condition>)
    return true;
else
    return false;

is redundant, and it's more readable to write

return <condition>;

instead. (maybe return <condition> != 0 if you need to always ensure a 0 or 1 result, but this is already the case in your code, since && and || are guaranteed to yield 0 or 1.)

like image 185
The Paramagnetic Croissant Avatar answered Dec 07 '25 15:12

The Paramagnetic Croissant


Yes they are. The first one is simply checking if both of them are true, and the second one checks if either of them are false. Both of them still return true if both are true, and false if not.

like image 45
Anuraag Varanasi Avatar answered Dec 07 '25 17:12

Anuraag Varanasi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!