Doubt in Call by reference | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

Doubt in Call by reference

I have a doubt in the program attached. I do understand that we are passing the address of 'a' and using the deferencing operator in the function. Inside the function, using the de-referencing operator, we are changing the value of a. But, my question is why is it mandatory to give sample(int *x) instead of just sample(int x). I understand that the value of 'a' will not be changed if * is not used. But, how do I put whatever happens technically? https://code.sololearn.com/cn4rn81VkvcX/?ref=app Plz help me with this. Thanks in advance Guyz!

5th Jan 2019, 11:12 AM
GOAT and The Shepherd
GOAT and The Shepherd - avatar
3 Answers
+ 2
void foo(int *x) { //I need a memory address : then I can access to the value stored at address X and modify it } void foo(int x) { //I want a value (not an address) }
5th Jan 2019, 11:27 AM
Théophile
Théophile - avatar
+ 2
I'd like to add, unlike variables and objects which by default are passed to functions by value, the default scheme for passing an array to a function like `f()` is done by reference — precisely, the name of the array is pointed to the first element of the array. In fact, It makes sense if you think of passing a large sequence of numbers by reference, otherwise, it should've been done by making a temporary array, copying a whole lot of numbers to it, and returning the entire array to the caller which require a tremendous amount of work. Example ~~~~~~~~~ void f(int arr[], int size) { // Also, `int *arr` can be used instead of `int arr[]` // do stuff... } int main() { int a[3] = {1, 2, 3}; f(a, 3); // passing the array by reference. }
5th Jan 2019, 1:22 PM
Babak
Babak - avatar
+ 1
Thanks Théophile . So, it is like mandatory to use a * if I need to access the address and change its value.
5th Jan 2019, 11:31 AM
GOAT and The Shepherd
GOAT and The Shepherd - avatar