-7

Point in Polygon Test Code

int pnpoly(int nvert, float *vertx, float *verty, float testx, float testy)
{
  int i, j, c = 0;
  for (i = 0, j = nvert-1; i < nvert; j = i++) {
    if ( ((verty[i]>testy) != (verty[j]>testy)) &&
     (testx < (vertx[j]-vertx[i]) * (testy-verty[i]) / (verty[j]-verty[i]) + vertx[i]) )
       c = !c;
  }
  return c;
}

What is the purpose of ! in c = !c; ?

snowpeak
  • 797
  • 9
  • 25
  • 7
  • haha, I know that ```!``` is NOT operator, but I don't understand why someone wants to flip the value from zero to non-zero and vice versa. – snowpeak Aug 22 '18 at 16:11
  • 1
    @ShiningGo The alternative in the code you posted would be to replace `c = !c;` with `c++;` (or `c = c + 1;`) and then return `c & 1` at the end, but what's wrong with doing it the original way? – Ian Abbott Aug 22 '18 at 16:25
  • ... although using `c++;` and returning `c` would give you a "winding number" rather than a simple "in/out" indication ... – Ian Abbott Aug 22 '18 at 16:37
  • It's counting parity. `c` is 1 when the total number of times the `if` has been true is **odd**. Looks like a [point in polygon test](https://en.wikipedia.org/wiki/Even%E2%80%93odd_rule). – Boann Aug 22 '18 at 21:17

2 Answers2

2

Any non-zero number or non-null pointer is considered to have a logical value of "true", whereas a number with value 0 or a null pointer is considered to have a logical value of "false".

The ! operator is the logical NOT operator (as opposed to a bit-wise NOT operator). It inverts the logical value of its operand, producing the integer value 0 if the operand has a logical value of "true", and the value 1 if the operand has a logical value of "false".

Ian Abbott
  • 15,083
  • 19
  • 33
0

! stands for logical NOT in C. So basically the value of c is being flipped from zero to non-zero and vice versa.

Sandy
  • 895
  • 6
  • 17