0
What is the difference between (value & reference) ???
I want clarification and examples if possible
4 Antworten
+ 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
+ 8
It's really a great practical example! :)
+ 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
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 }