What is the difference between (value & reference) ??? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

What is the difference between (value & reference) ???

I want clarification and examples if possible

11th Sep 2017, 5:41 PM
Ahmed Mohammed Ahmed Khodary
Ahmed Mohammed Ahmed Khodary - avatar
4 Answers
+ 8
For primitive types like int, double, char etc., when a variable is passed to a method, actually a COPY (value) of the variable is passed. So whatever you'll do inside that method, it won't affect the original variable. For non-primitive types like object, array, String etc., the REFERENCE (memory address) is passed to another method. And then the changes inside the method will modify the passed variable. https://code.sololearn.com/c613pBjuPn1q/?ref=app
11th Sep 2017, 6:34 PM
Shamima Yasmin
Shamima Yasmin - avatar
+ 8
It's really a great practical example! :)
11th Sep 2017, 7:42 PM
Shamima Yasmin
Shamima Yasmin - avatar
+ 1
@Shamima Yasmin thanks very much .. I think this can help if another one asked the same question ..👇 https://blog.penjee.com/wp-content/uploads/2015/02/pass-by-reference-vs-pass-by-value-animation.gif
11th Sep 2017, 7:27 PM
Ahmed Mohammed Ahmed Khodary
Ahmed Mohammed Ahmed Khodary - avatar
0
#include <iostream> void by_val(int arg) { arg += 2; } void by_ref(int&arg) { arg += 2; } int main() { int x = 0; by_val(x); std::cout << x << std::endl; // prints 0 by_ref(x); std::cout << x << std::endl; // prints 2 int y = 0; by_ref(y); std::cout << y << std::endl; // prints 2 by_val(y); std::cout << y << std::endl; // prints 2 }
11th Sep 2017, 5:48 PM
MsJ
MsJ - avatar