views:

154

answers:

4

Hello everyone,

I am a new student in the compilers world ^_^ and I want to know is legal represent negative number in the stack.

For example:

infix: 1-5=-4 postfix: 15-

The statements are:

push(1)
push(5)
x=pop()
y=pop()
t=sub(y,x)
push(t)

The final result in the stack will be (-4)

How can i represent this if it is legal??

Thank you ^_^

+2  A: 

Yes. Negative numbers are stored in Two's complement form in memory, so you don't need an additional cell on the stack for the sign.

Aaron Digulla
A: 

If you talk about a stack you talk about abstract data types. As long as you have a push/pop functionality it makes no difference what you put in the stack

alinrus
A: 

First note that there is a difference between the dash, '-', used as the subtraction operator and as the negative sign. Though we use the same character, they have a different meaning.

Both positive and negative integers, like -4, take only a single slot in the stack.

If your postifx language can only take single-digit integers and the arithmetic operators, you can represent negative numbers by subtracting from zero:

04-2+

This is equivalent in infix notation to

0-4+2

Here is some terminology: the subtraction operation is a "binary operator," that is, it takes two operands; the negative sign is a "unary operator," that is, it takes one operand. Infix and postfix are notations for binary operators and their operands.

Paul
+1  A: 

In case you are referring to representing the expression textually (perhaps in a file that is read in by your program), then you would probably define some syntactic rules for your expression - say separation of tokens by whitespace

For example, is 444/ in postfix the same as (4 / 44) or (44 / 4) or (4 / (4 / 4)) in infix? You would need some way of seperating multi-digit numbers.

Now, assuming you decide on whitespace, you could make a rule that a negative integer would be a minus sign followed by a series of digits without any separating whitespace

So the infix expression '-1 * (3 ^ (-4) - 7' could become '-1 3 -4 ^ * 7 -'

Is this what you were looking for?

PS - With a proper parser, you could actually do it without whitespace for operators, but you still need to separate operands from each other.

Gautham Ganapathy