简体   繁体   中英

C++ - Calculating final values of x and y with a specific function

I really do not have any clue about how to solve this task, can someone please help?

Consider the following function definition:

void f(int i, int &j) {
    j = i+1;
    i = j*2;
    j += i; 
}

In the following code:

int x = 4, y = 7;
f(x, y);

What are the final values of x and y ?

For starters you could just run the code... but otherwise we can try and predict the output.

For starters the function f has two parameters, i and j. The & Infront of the j means that the value of the function input is passed by reference (the value of the variable will be edited).

So now let's evaluate the function with inputs 4, 7. We get:

j = 4+1 = 5
i = 10
j += i, j = 15

Because the variable y was passed by reference, its value will become 15. The variable x was passed by value, so it doesn't get affected and thus stays as 4.

Simply just run the code.Anyway the output will be

x=4(because it is passed as pass by value ->any change will not affect the outside the function f) y=15(because it is passed as pass by reference->any change will affect the outside the function f)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM