+ 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; }
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
}
+ 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
+ 2
x is passed to myFunc by reference, not by value.
+ 2
Sreejith thank you alot it really helped
0
Damyan Petkov thank you but whats the main difference between passing by reference and by Value?