+ 1

Please someone tell me why the output of var is 100 and not 20?? 😮

#include <iostream> using namespace std; void myFunc(int *x) { *x = 100; } int main() { int var = 20; myFunc(&var); cout << var; }

6th Apr 2018, 2:46 PM
RiGeL
RiGeL - avatar
6 Respostas
+ 1
reference -> passes the address of variable, any changes to the variable in myfunc affects the variable in main eg : void fun(int *c) { c= 200;} main () { int x= 3; fun(&x); cout << x ; //output 200 } value -> passes a copy of value as parameter eg: void fun(int c) { c= 200;} main () { int x= 3; fun(x); cout << x ; //output 3 }
6th Apr 2018, 4:08 PM
‎ ‏‏‎Anonymous Guy
+ 3
originaly the value of var is 20, then you call myFunc passing as reference the memory direction of var, so now x points to var. Inside of the function you assign 100 to the value of x (x points to var) so var = 100 , then you print var which value is 100
6th Apr 2018, 2:57 PM
J Domingo Jiménez J
J Domingo Jiménez J - avatar
+ 2
x is passed to myFunc by reference, not by value.
6th Apr 2018, 3:14 PM
Damyan Petkov
Damyan Petkov - avatar
6th Apr 2018, 3:18 PM
Damyan Petkov
Damyan Petkov - avatar
+ 2
Sreejith thank you alot it really helped
6th Apr 2018, 4:12 PM
RiGeL
RiGeL - avatar
0
Damyan Petkov thank you but whats the main difference between passing by reference and by Value?
6th Apr 2018, 3:16 PM
RiGeL
RiGeL - avatar