0

why is it equal to 7?

#include <iostream> #include <string> using namespace std; void foo(int &k){ k*=2; } int main() { int x=2,y=3; foo(x); cout << x + y; return 0; }

24th Sep 2019, 9:56 AM
汝風留名
汝風留名 - avatar
6 Réponses
0
Because &k means that you are passing the memory address of k, in this way is possible to change the actual value of k. Without ampersand you pass a copy of k, so foo acts on this copy and not on the actual value.
24th Sep 2019, 10:07 AM
AndreaC
AndreaC - avatar
0
Its simple I'll explain you how: When you are calling function foo() with parameter x which has a value 2. Then it stored in k but k is not simple variable of int type but it's taking value of that address where 2 is stored. Then you do simple maths now k = 2 and k*=2 is k= k*2 , k=4 now it changed the value of 2 which was stored at that address to 4 now you don't need to return because it changes the value of x =2 to x= 4 Then cout<<x+y; gives you 4+3 = 7 Therefore, it gives you output 7.
24th Sep 2019, 10:10 AM
Chirag Kumar
Chirag Kumar - avatar
0
Thx~
24th Sep 2019, 10:10 AM
汝風留名
汝風留名 - avatar
0
i was thinking that k* was refering to the value of that address instead of k = k*2 xd
24th Sep 2019, 10:14 AM
汝風留名
汝風留名 - avatar
0
it should be *k instead of k* for the value xd
24th Sep 2019, 10:19 AM
汝風留名
汝風留名 - avatar