0

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?

Barmak Shemirani
  • 30,904
  • 6
  • 40
  • 77
sajjad eshghi
  • 69
  • 1
  • 5

2 Answers2

2

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
Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
  • 2
    Careful, `!( a == b ) operator !( c == d )` is not the same as `a != b operator c != d`, when _operator_ is `+, -, *, /, >>, others` due to precedence differences. – chux - Reinstate Monica Dec 06 '21 at 00:11
2

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.

chux - Reinstate Monica
  • 143,097
  • 13
  • 135
  • 256
  • 1
    The macros in `` are reserved by the C Standard, so your native code should not be using them. – Andrew Dec 06 '21 at 06:24
  • 1
    @Andrew True that code _should_ not be defining them, yet the impact of including `` remains surprising for many with its `and, or, not`. I do not see it as much of a problem with new code, but with the inclusion of various established user `"*.h"` files. – chux - Reinstate Monica Dec 06 '21 at 15:10