views:

25

answers:

1

All,

When we are passing an expression as a parameter, how does the evaluation occur? Here is a small example. This is just a pseudocode kind of example:

f (x,y)
{
    y = y+1;
    x = x+y;
}
main()
{
    a = 2; b = 2;
    f(a+b, a)
    print a;
}

When accessing variable x in f, does it access the address of the temp variable which contains the result of a+b or will it access the individual addresses of a and b and then evaluate the value of a+b

Please help.

Regards, darkie15

A: 

Somewhat language dependent, but in C++

f(a+b, a)

evaluates a + b and and pushes the result of evaluation onto the stack and then passes references to this value to f(). This will only work if the first parameter is of f() is s const reference, as temporary objects like the result of a + b can only be bound to const references.

anon
So when the value of y changes with y = y+1, the next statement i.e. x = x+y will still have y = 2 right?
darkie15
@dark No - if the value of y is changed, why would you think the next statement finds it unchanged?
anon
@Neil: That is what my initial question was, will 'y' point to the address of the temp variable where the result is stored of the evaluation of expression (a+b). At the time of call, a = 1 and b =2. So the expression is evaluated and the address where this result is stored is binded with the formal parameter 'y'. Am I right here?
darkie15
@dark Your original question did not ask that. a+b is evaluated and the result is bound to the formal parameter x (not y). All of this would be easier to answer if you used a real programming language in your question.
anon

related questions