Post Reply 
Unary minus precedence preference
07-23-2014, 04:16 AM
Post: #12
RE: Unary minus precedence preference
(07-23-2014 03:14 AM)htom trites Wrote:  Do you take -2^2 to mean: (-2)^2, -(2^2), or 0-(2^2)?

I've always taught that unary minus is the last (and should be parsed as if it was that by a computer), even though it's usually written as the second.

(I admit I came to this conclusion writing a compiler that emitted code for both one's and two's complement ALUs.)

In the context of a compiler, it needs to be dependent on the standard of the language in question. Dig far enough into any language standard and you should find (1) precedence rules for the exponentiation and unary minus operators, and (2) a precise definition of what is meant by the unary minus.

The C standard sidesteps this issue in part by not providing a built-in exponentiation operator. It has this to say about the unary minus: "The result of the unary - operator is the negative of its (promoted) operand." This may leave some room for interpretation and implementation of "negative," but this is generally well-defined in the context of established binary integer representations and floating-point standards.

So, again, it essentially comes down to a convention. And any language that does not specify a clear-cut convention for operations like -2^2 is certainly asking for trouble!

John
Find all posts by this user
Quote this message in a reply
Post Reply 


Messages In This Thread
RE: Unary minus precedence preference - John R - 07-23-2014 04:16 AM



User(s) browsing this thread: 1 Guest(s)