NOT(~) vs NEGATION(!)

When i gets to -1, the value of ~i is ~-1, or 0, so the while loop stops executing. The ! operator works because it does something completely different; it results in 1 for 0 values and 0 for all other values. ~ is a bitwise negation.

A little more in detail:

  • ~ takes each bit in a number and toggles it. So, for example, 100102 would become 011012
  • -1 is all ones in binary when a two’s complement signed integer.
  • ~0b…11111111 is 0.

However:

  • !0 is 1, !anythingElse is 0
  • -1 is not 0
  • !-1 is still 0

And if you actually want to loop including i == -1, just use while (i) instead of while (~i).

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)