Question

I've been using the Stanford videos as a tool for learning iOS programming. I have a question about the "-" operation. The walk through explains that for this part of code the order of operands has to be correct. I don't get how this piece of codes assures the order of operations. What is this doing?

else if ([operation isEqualToString:@"-"]) {
double subtrahend = [self popOperand];
result = [self popOperand] - subtrahend;

I get the first line of code bud I don't understand the last 2 lines. How is putting a double in to subtrahend variable and setting it equal to popOperand assuring the order of operations and then subtracting subtrahend from [self popOperand]?

Was it helpful?

Solution

What they're saying is just that you need to make sure to pop the subtrahend before the minuend because of the order they're placed on the stack, otherwise you get the wrong result.

Put simply, 5 - 3 != 3 - 5.

OTHER TIPS

Use NSLog to output a useful message at each intermediate step, and it should be obvious what's going on here. Useful technique in many situations.

The other way to think about this is that you want to subtract the first thing off the stack from the second thing off the stack. Or if you prefer, express the operation this way:

    result = - [self popOperand] + [self popOperand];

It might just work, but of course this is assuming that the left-most popOperand is being executed first.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top