2

I am looking at someone else's code and I am trying to figure out what they are doing. The snippet in question looks like the following:

for(j in a)     
  for(i in a)
    y=a[i]+-~j,b=a[j]

I understand the y=a[i] part, but what does +-~j do?

mhodges
  • 10,938
  • 2
  • 28
  • 46
Bryro
  • 222
  • 1
  • 14
  • 1
    Great example of how not to write code! Ever! – Molik Miah Sep 28 '17 at 20:02
  • 3
    Possible duplicate of [What does a tilde do when it precedes an expression?](https://stackoverflow.com/questions/12299665/what-does-a-tilde-do-when-it-precedes-an-expression) – user3351605 Sep 28 '17 at 20:50

1 Answers1

9

This is (kind of?) clever use of the tilde (~) operator, but it just leads to confusion. The ~ (effectively) adds one to the number and flips the sign.

~0 === -1

~1 === -2

~-1 === 0

etc.

The - flips the sign back to what it originally was.

So the end result of -~j is j + 1

This then gets added to a[i] and assigned to y

Moral of the story: don't ever write code like this.

Note: There are legitimate use-cases for the ~ operator, most notably in the .indexOf() function. If you want to check if something was found in an array/string, rather than saying:

if (arr.indexOf("foo") > -1) {...}, you can say

if (~arr.indexOf("foo")){...}. This is because if the value is not found, indexOf() will return -1, which, when passed through the tilde operator, will return 0, which coerces to false. All other values return 0 through n, which return -(1 through n+1) when passed through the tilde operator, which coerce to true.

Community
  • 1
  • 1
mhodges
  • 10,938
  • 2
  • 28
  • 46