In part of a code I saw this phrase:
!(word[i]==(tmpP->word[i]))
is it equal to
(word[i] != (tmpP->word[i]))
?
What is the difference between these two expressions?
CodePudding user response:
The expression
!(word[i]==(tmpP->word[i]))
is logically equivalent to the expression
(word[i] != (tmpP->word[i]))
Another example
!( a == b && c == d )
is equivalent to
!( a == b ) || !( c == d )
that is, in turn, equivalent to
a != b || c != d
CodePudding user response:
what is the difference between these two expressions?
One can use a != b
or !(a == b)
interchangeably1. Both use a, b
once and both evaluate to an int
of value 0 or 1.
Use the one most clear for the context of code (which is usually the first, but the seconds binds tighter.)
How can we write "not equal" in c?
Standard C has alternate spellings macros in <iso646.h>
(since C94) including not_eq
.
and &&
and_eq &=
bitand &
bitor |
compl ~
not !
not_eq !=
or ||
or_eq |=
xor ^
xor_eq ^=
Example
#include <iso646.h>
#include <stdio.h>
#include <time.h>
int main() {
srand((unsigned)time(0));
int a = rand()%2;
int b = rand()%2;
if (a not_eq b) puts("Not equal.\n");
else puts("Equal.\n");
}
Use <iso646.h>
with caution as the macros may collide with existing code names.
1 !
has higher precedence than !=
, so with more complex expressions, be careful. When in doubt, use an outer ()
: (a != b)
versus (!(a == b))
are truly the same.