Quote:
Originally Posted by dina3e
ok , fine i agreed with your answer ,
but when i am trying to solve this
a = ++a + ++a;
answer is 14 how this result is possible.
Plz suggest how all these thing are done in stack. Mean how push and pop operation happen during the ++ (pre and post increment operation)
|
This sounds like a wacky question professors give you to try and make you really understand how something works (the compiler in this case and the way it uses a stack to execute mathematical expressions). I think a useful and interesting observation in this example is that the compiler doesn't store the value of a variable in the stack, instead it stores a pointer to a variable in the stack.
There are a few different ways to use a stack to correctly evaluate a mathematical expression while following the orders of operation.
I will do an example of a version the scans the expression from LEFT to RIGHT (this would be easier with a white board to visually represent the stack, but I will try with words. You should go along with this and create your own 'visualized' stack of what's going on on a piece of paper).
Code:
a=5;
a= a + ++a + ++a + ++a;
1. LEFT to RIGHT way
-A pointer to the variable 'a' is pushed on the stack
-An '=' is pushed on the stack
-A pointer to 'a' is pushed on the stack
-A '+' is pushed on the stack
-the operation '++a' is carried out on 'a' and 'a' now equals 6
-the '+' is popped off the stack
-the 'a' is popped off the stack
-the expression 'a' + 'a' is evaluated to 12 (since a=6)
-the VALUE 12 is pushed onto the stack
-A '+' is pushed onto the stack
-the operation '++a' is carried out on 'a' and 'a' now equals 7
-the '+' is popped off the stack
-the VALUE 12 is popped off the stack
-the expression 12 + 'a' is evaluated to 19(since a=7)
-the VALUE 19 is pushed on the stack
-A '+' is pushed on the stack
-the operation '++a' is carried out on 'a' and 'a' now equals 8
-the '+' is popped of the stack
-the '19 is popped off the stack
-the expression 19 + 'a' is evaluated to 27(since a=8)
-the '=' is popped off the stack
-the 'a' is popped off the stack
-the operation a = 27 is evaluated
-a=27
This is one way of doing it. I have no clue how your compiler (or mine for that matter) actually does it. But this is one way it could do it.