Reputation:
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
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
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
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
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:
Upvotes: 2
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