r/ProgrammerTIL • u/DewJunkie • May 16 '18
Other TIL - is a unary operator in many languages
I always thought that you had to do x*-1
-x == x * -1Not world changing I guess, but surprised me when I saw it.
edit:formatting
26
Upvotes
28
u/HaniiPuppy May 16 '18
Also, + is a unary prefix operator in most languages as well, to complement -. It does literally nothing.
6
u/redditsoaddicting May 16 '18
You can put code in backticks (`) so that x*-1 doesn't start italics. Your second line also needs to be separated by a blank line for the code block to format properly.
21
u/Da_Drueben May 16 '18 edited May 16 '18
Some calculators have two buttons for the minus signs, one for the binary operator and one for the
binaryunary operator. It's as terrible as it sounds.Edit: the most important word of the sentence
11
u/acqd139f83j May 17 '18
I read "TIL is an unary operator in many languages" and I guess it is in English. It takes facts and returns expressions of experience that are somehow relatable.
3
u/night_of_knee May 17 '18
If you think of this a bit more you'll realize that the
-inx * -1is the unary minus operator applied to1.Are there languages that don't have a unary minus operator?
2
u/eddieSullivan May 22 '18
It works out that way, but at a conceptual level and at an (unoptimized) machine code level they are different. Negation for an integer means to take the twos-complement, while multiplication is a different operation, even if it's by -1.
1
u/JavaSuck May 18 '18
The
-in-1is the same unary operator as in-x, btw :)1
u/zehydra May 16 '18
Yeah, it depends on the language. I have run into at least one language that I was using that didn't have it.
-2
u/CompellingProtagonis May 16 '18
Do you mean -- ? The - operator is negation. I could be misunderstanding, though, so I apologize if that's the case.
-9
u/gabriel-et-al May 16 '18
If you mean
--xthen it's called "prefix decrement". There are others too.