Tallan's Blog

Tallan’s Experts Share Their Knowledge on Technology, Trends and Solutions to Business Challenges

Posts Tagged "reference"

Pass by reference

In C++ and C#, developers have freedom to modify variables by directly having access to memory location.
In C++,
#include <stdio.h>
void swapnum(int &i, int &j) {
int temp = i;
i = j;
j = temp;
int main(void) {
int a = 10;
int b = 20;
swapnum(a, b);
printf(“A is %d and B is %d\n”, a, b);
return 0;
In C#,
int a = 1;
modify(ref a); //now a=2
void modify(ref int a)
a = 2;
In Java, however, there’s no such thing as pass by reference.  Even the so-called pointers (created by ‘new’ operator) are passed by copy of the reference.
Thus, if you do the following,
String a = “a”;
modify(a); //a doesn’t change, since a is being passed as a copy of the pointer a.
void modify(String a)
a = “b” //this a is a different pointer, thus does not affect the real ‘a’ pointer outside of the method.
As you can see, there’s no direct way of modifying…