3

The docs say that ! is "Boolean not. Implements three-valued logic" and ~ is "Bitwise not."

When should one be used versus the other?

There is a similar question for Python about comparison operators, but I am not sure where the languages may differ.

Alec
  • 4,235
  • 1
  • 34
  • 46

1 Answers1

5

As you say, ! is boolean not and ~ is bitwise not. This ends up being a bit redundant since bitwise not for booleans is just boolean not so anywhere you can use ! you should also be able to use ~. (This is always true with standard Julia should remain true as long as package don't addg methods that don't conform to the intended meaning of these operators.) So if you're a Matlab programmer, for example, and you're used to using ~ for boolean not, then you can keep doing that. My suggestion, however, would be to be as precise in your meaning as you can be: if you expect the argument to be boolean, use ! so that you get an error if it isn't. Use ~ if you expect the argument to be an integer and want to flip its bits. But frankly it's no big deal to use ~ for booleans. If it really matters that the argument is boolean, like if it's being used in a conditional, then the error will show up soon anyway.

There was a discussion in the lead up to the 1.0 release about removing ! from the language and using ~ for boolean negation instead, but we ended up keeping ! because it's familiar from languages like C and C++ and giving it any other meaning would be actively confusing. But it's telling that removing it was an option in the first place.

StefanKarpinski
  • 32,404
  • 10
  • 86
  • 111