33.1k views
2 votes
The following problem illustrates the way memory aliasing can cause unexpected program behavior. Consider the following function to swap two values

void swap(int xp, int yp)
If this procedure is called with xp equal to yp (i.e. both xp and yp point to the same integer) what effect will it have compared to the situation where xp and yp point to different integers?
a. The value will ahways be the original value in the integer pointed to by xp.
b. It is not possible for xp and yp to have the same value
c. The value will always be zero.
d. The value will always be the original value in the integer pointed to by yp.
e. It will be the same - doesn't matter

1 Answer

4 votes

Answer:

A

Step-by-step explanation:

The value will be the original stored in the int variables. This is because the method swap(int xp, int yp) accepts xp and yp parameters by value (They are passed by value and not by reference). Consider the implementation below:

public class Agbas {

public static void main(String[] args) {

int xp = 2;

int yp = xp;

swap(xp,yp); //will swap and print the same values

System.out.println(xp+", "+yp); // prints the original in values 2,2

int xp = 2;

int yp = 5;

swap(xp,yp); // will swap and print 5,2

System.out.println(xp+", "+yp); // prints the original in values 2,5

}

public static void swap(int xp, int yp){

int temp = xp;

xp = yp;

yp = temp;

System.out.println(xp+", "+yp);

}

}

User Compoot
by
6.6k points