user2935354
user2935354

Reputation:

Logical && and Logical || operator confusion

I found below code line in a opensource project:

if(WIFSTOPPED(status) && WSTOPSIG(status) == SIGTRAP)

I am not able to understand this code. According to code flow this should be(I am sure):

if((WIFSTOPPED(status) == SIGTRAP) || (WSTOPSIG(status) == SIGTRAP))

Are both the same??

Upvotes: 1

Views: 173

Answers (5)

David Heffernan
David Heffernan

Reputation: 612964

The two code samples you offer are not the same. This

if (WIFSTOPPED(status) && WSTOPSIG(status) == SIGTRAP)

is equivalent to:

if (WIFSTOPPED(status) != 0 && WSTOPSIG(status) == SIGTRAP)

which is equivalent to:

if (!(WIFSTOPPED(status) == 0 || WSTOPSIG(status) != SIGTRAP))

which is clearly different from:

if ((WIFSTOPPED(status) == SIGTRAP) || (WSTOPSIG(status) == SIGTRAP))

Do note also that the C operator precedence has == and != as higher precedence than && and ||. Which means that the previous line of code is equivalent to:

if (WIFSTOPPED(status) == SIGTRAP || WSTOPSIG(status) == SIGTRAP)

The rules for logical operators that you need to know are:

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

and

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

Upvotes: 8

matrika ghimire
matrika ghimire

Reputation: 1

That means ::

In case WIFSTOPPED is bool:

if ( (WIFSTOPPED(status) != false) && *(WSTOPSIG(status) == SIGTRAP) )

In case WIFSTOPPED is string

if ( (WIFSTOPPED(status) != '') && *(WSTOPSIG(status) == SIGTRAP) )

In case WIFSTOPPED is integer:

if ( (WIFSTOPPED(status) != 0) && *(WSTOPSIG(status) == SIGTRAP) )

Upvotes: 0

user3373828
user3373828

Reputation:

Both are absolutely different.... First condition will apply when WIFSTOPPED(status)==0 and WSTOPSIG(status) == SIGTRAP... Second condition will apply when WIFSTOPPED(status) == SIGTRAP) or (WSTOPSIG(status) == SIGTRAP)

Upvotes: 0

Maroun
Maroun

Reputation: 95958

No, they're not the same.

if(0) is false in C, any other value considered to be true.

When you write:

if(WIFSTOPPED(status) && WSTOPSIG(status) == SIGTRAP)

Then if WIFSTOPPED(status) returns 0, the other side won't be evaluated due to Short-circuit evaluation.

It's like writing:

if(WIFSTOPPED(status) != 0 && WSTOPSIG(status) == SIGTRAP)

De-Morgan's laws should be very helpful for you:

  • "not (A and B)" is the same as "(not A) or (not B)"
  • "not (A or B)" is the same as "(not A) and (not B)"

Upvotes: 2

naffy
naffy

Reputation: 111

no they are not the same

the && means that both conditions must be true for the if statement to be true.

i dont know what WIFSTOPPED(status) does but in the second statement it doesnt have to equal SIGTRAP if (WSTOPSIG(status) equals SIGTRAP

while in the first statement WIFSTOPPED(status) must return true AND (WSTOPSIG(status) equals SIGTRAP

Upvotes: 0

Related Questions