简体   繁体   中英

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??

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

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

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

两者都是绝对不同的。...第一个条件将在WIFSTOPPED(状态)== 0且WSTOPSIG(状态)== SIGTRAP时适用...第二个条件将在WIFSTOPPED(状态)== SIGTRAP)或(WSTOPSIG(状态) == SIGTRAP)

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

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM