5. What is printed by the following code fragment?

int x = 5, y = 3, *p = &x, *q = &y;

std::cout << "x = " << x << ", y = " << y << '\n';

x = y;

std::cout << "x = " << x << ", y = " << y << '\n';

x = 7;

std::cout << "x = " << x << ", y = " << y << '\n';

*p = 10;

std::cout << "x = " << x << ", y = " << y << '\n';

p = q;

*p = 20;

std::cout << "x = " << x << ", y = " << y << '\n';​

Respuesta :

Output:

x = 5, y = 3

x = 3, y = 3

x = 7, y = 3

x = 10, y = 3

x = 10, y = 20

Explanation:

Here x and y is variables are assigned with value of 5 and 3, the pointers p, q are assigned to base addresses of y and x. While executing the first cout statement, the values of 5,3 is printed for x,y.  Then next statement is   x = y which means y value is assigned to x and the second cout statement is executed, so here the values of x,  y  are  equal to 3  respectively.

Since the variable p points to base address of x and its value is be changed 10, so x = 10.Now when the third cout statement is executed so  x  changed to 10 and y is 3.Now the value of q(base address of y) is assigned to p and the value of p(using dereferencing operator *) gets assigned the value of 20.So while executing the fourth cout statement, the values of x and y are 10 and 20 respectively. The output is given below.

ACCESS MORE
EDU ACCESS
Universidad de Mexico