call by value call by reference difference

Feb 20, 2009 at 5:34pm
Can anyone please explain the difference between call by value and call by reference in simple words , I read the explaination here but didn't get it.
please tell me in simple words.
Feb 20, 2009 at 5:52pm
When passing data by value, the data is copied to a local variable/object in the function. Changes to this data are not reflected in the data of the calling function. For larger objects, passing data by value can be very expensive.
When passing data by reference, a pointer to the data is copied instead. Changes to the data pointed to by the pointer are reflected in the data of the calling function. Regardless of the size of the object, passing data by reference always has the same cost.

Example:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
void by_value(int a){
	a+=10;
}

void by_ref(int *a){
	(*a)+=10;
}

void by_ref2(int &a){
	a+=10;
}

int main(){
	int x=40;
	by_value(x);
	//x==40
	by_ref(&x);
	//x==50
	by_ref2(x);
	//x==60
	return 0;
}

by_ref() demonstrates the syntax used to pass data by reference using pointers. by_ref2() demonstrates the syntax used to pass data by reference using references.
Do not confuse passing by reference with passing with references. It's possible to pass by reference without passing with references, but passing with references always passes by reference.
Last edited on Feb 20, 2009 at 5:55pm
Feb 21, 2009 at 12:41am
Can I say that whenever the function has & sign it is call by reference and whenever a function doesn't have any & sign , the function is call by value always and for sure.
Last edited on Feb 21, 2009 at 12:42am
Feb 21, 2009 at 12:56am
Parameters are passed by value, reference, or pointer. A reference parameter looks like line 9 above.

You can have a function that takes multiple parameters - some by reference, some by value, some by pointer.

Feb 22, 2009 at 4:22am
Can I say if the parameters within the function has * or & in it ,it is call by reference otherwise call by value ?
Feb 22, 2009 at 4:37am
Feb 22, 2009 at 5:15am
Please !! Answer in yes or no .

Can I say if the parameters within the function has * or & in it ,it is call by reference otherwise call by value ?
Last edited on Feb 22, 2009 at 5:16am
Feb 22, 2009 at 5:43am
Yes.
Feb 22, 2009 at 6:17am
does it mean that if the function has pointer in it , it is always call by reference ?
Feb 22, 2009 at 7:38am
Could you give an example?
Feb 22, 2009 at 8:12am
like when the function is call by reference if the parameters have * and & signs similarly, pointers have * and & signs ,
so what is the relation between pointers and call by reference ?
Topic archived. No new replies allowed.