0
Can anyone explain the code step by step? Can't understand what happened after function location was called. Thank you.
#include <iostream> using namespace std; void location(int &x,int y=4) { y+=2; x+=y; } int main() { int px=10,py=2; location(py); location(px,py); cout<<px<<py; }
6 Answers
+ 8
At first call : location(2)
px will not change because it is not passed, so will remain as 10
py will change to 8(in function py is nothing but x) as
y=4+2=6
x=2+6=8
Because it is called by reference
Here px=10 py=8
After call :location(10,8)
px value will only be chang becaus Here it is called by reference
y=8+2=10
x= 10+10=20
Here px=20 py=8
And just check out parameter passing methods.
+ 3
void location(int &x,int y=4)
{
y+=2;
x+=y;
}
int main()
{
int px=10,py=2;
location(py); // You make a call to the function by passing the value of py but the function takes it's address as an argument in the variable x. So any change to x will be reflected in py as well. The 2nd parameter in the function int y=4 is a default variable which is used when we don't have a second parameter to pass while calling the function.
So y=4 then inside the function y+=2 which is 4+2=6 and x is 2 already so in next line x becomes 2+6=8. Now since x refers to py, the value of py is changed to 8.
location(px,py); // here you are again calling the function by passing px and py, so similarly the reference of px is held by x and it would alter the value of px directly but now y will not have the default value of 4 since the second parameter py is also passed so now y becomes 8(see the above explanation). So inside the function y+=2 will be 8+2=10;
+ 1
Continue.....
Your px which is pointed by x is already 10 so in the next line of function x+=y you will get 10+10=20.
So finally your px value is 20 and your py value is 8.
cout<<px<<py; // output 208
+ 1
Thank you Avinesh and Ozair Khan
0
Hi
0
Where are you from?