开发者

Specific Parameter-Passing Styles: Call-By-Value, Call-By-Name, etc

开发者 https://www.devze.com 2023-01-29 03:55 出处:网络
Studying for my final exam, and came across this past exam question: Consider the following program written in a C-like notation:

Studying for my final exam, and came across this past exam question:

Consider the following program written in a C-like notation:

int i = 1;
A[开发者_开发百科] = {4, 0, 1, 2};

void mystery05(int from, int to)
{
    int temp;
    temp = A[from];
    A[from] = A[to];
    A[to] = temp;
    i = i + 2;
    to = -1;
}

int main(void)
{
    mystery05(A[i+2], A[i]);
}

In the table below, fill in the boxes with the appropriate variable values after the call to mystery05 in main. Each row corresponds to a specific parameter-passing style (ie. use the style listed instead of the default C-language semantics). Assume arrays are indexed from 0.

style               |___i___|__A[0]__|__A[1]__|__A[2]__|__A[3]__| 
call-by-value       |_______|________|________|________|________|
call-by-name        |_______|________|________|________|________|
call-by-reference   |_______|________|________|________|________|
call-by-value-result|_______|________|________|________|________|

I'm not sure on how to go about this, but if it was regular C semantics, I supposed the answers would be

i = 3; A[0] = 4; A[1] = 2; A[2] = 1; A[3] = 0


@S.Lott : I thought 'pointer's to strings and arrays are call by reference. Am I wrong?

I agree: don't want to do all the question. If he has an exam he ought to be more clued up. I would like to answer the first line though just to see if i have understood correctly. So I could be wrong!

Call by value: doesn't change the values unless the variables are global and in this case they have to be; for how otherwise can the proc make use of i.

Both i and the A array are global.

What happens in the proc changes the values.

i begins with value 1 so values of A[3] and A[1] swapped.

A[3] now 0 , A[1] now 2 . A[0] and A[2] unchanged.

finally i value changed to 3

I think the exam q missed a trick by not asking about the value of 'to' after the proc call.


call-by-value is -- I think -- what you mean by "regular C semantics"

call-by-name is something C doesn't have. Look it up. That's not "regular C semantics"

call-by-reference assumes that all the arguments have "&" and the parameters have "*". That's not "regular C semantics" that's a different semantics, but easily built in C.

call-by-value-result is something C doesn't have. Look it up.

Each is different. Don't assume C. Don't read the code as if it was C. You have to read the code in different ways assuming different things.

0

精彩评论

暂无评论...
验证码 换一张
取 消