r/C_Programming • u/YOYOBunnySinger4 • Jul 05 '26
Difference between pass by value, pass by pointers and pass by reference?
what are their differences? and what are they exactly?
51
Upvotes
r/C_Programming • u/YOYOBunnySinger4 • Jul 05 '26
what are their differences? and what are they exactly?
120
u/bluetomcat Jul 05 '26 edited Jul 05 '26
C is a “pass by value” language with value semantics. Pointers themselves are also passed by value. It just so happens that a pointer is a means for indirection. Also, things that aren’t pointers (arrays), pretend to be pointers in certain contexts.
26
u/SufficientGas9883 Jul 05 '26
When a function is called it receives a number of argument values. These are handed to the callee in CPU registers and/or on the stack (depending on the ABI bu we don't care about that right now).
These argument values can be fully modified by the callee function, but since they're the callee's own local copies, modifying them does not affect the caller.
Now, your question is about what value is actually passed to the callee:
Note that C itself only ever passes by value. "pass by pointer" is just passing a pointer value by value.
In C++, there is a separate notion of "reference" variables. Under the hood (i.e., compiled code) it's still essentially pass by pointer, but it has more restrictions than a regular pass-by-pointer (e.g., a reference can't be null in well-defined code and can't be reseated). Modern C++ discourages raw pointers.
13
u/nemotux Jul 05 '26
Pass by value means the function gets a copy of the parameter.
Pass by pointer means the function gets a pointer to the parameter. Pass by reference is a synonym for this in C.
In the latter case, if the function modifies the value of the parameter, that modification is visible in the calling function. In the former case, that doesn't happen because the function has its own copy of the parameter.
This kind of side effect is one reason one might want (or not want) to pass by pointer/reference.
The other difference is if the parameter is large (an array or large struct), pass by pointer avoids needing to spend time copying the whole thing. Where as pass by value can be more efficient for scalar values, since you avoid the function needing to dereference the pointer to access the parameter.
6
u/SmokeMuch7356 Jul 05 '26 edited Jul 06 '26
Pass by value: the argument expression is evaluated and the result of that evaluation is copied to the corresponding formal argument. Given:
aandxare different objects in memory; the argument expressionais evaluated, and the result (5) is copied tox. The update toxhas no effect ona. Pass by value means you can pass literal arguments:or the result of an arithmetic expression:
or even the result of another function call:
Pass by pointer: is a variation of pass by value; you're still evaluating the argument expression and copying the result to the formal parameter:
aandxare still different objects in memory, changes to one have no effect on the other, etc. However, instead of getting a copy of the value stored ina,xgets a copy of its address. The expression*xacts as a kinda-sorta alias fora:so writing to
*xis the same as writing toa. Literals like5do not have an address, so you can't write something likeand any arithmetic or other expression must yield a pointer value:
and any function call must yield a pointer:
Pass by reference: the formal argument is an alias for the actual argument; it is not a separate object with its own storage and lifetime.1 C does not support pass by reference in any form, so we'll use C++ as the example:
In this case,
xis just an alias fora; writing toxis the same as writing toa.3
u/Tinolmfy Jul 05 '26
You either
copy the content of that variable
or you copy the address to that variable
or you copy the address of that variable and act like it's the original thing
3
u/generally_unsuitable Jul 06 '26
In this thread, people will do somersaults to tell you that a pointer is not a reference, despite K&R using that terminology many times. That's why there's a "dereference" operator. Why would you dereference something that isn't a reference?
2
u/Living_Fig_6386 Jul 06 '26
C has pass by value. That value can be a pointer.
The values function receives are copies of the values passed to the function. You typically don’t pass very large structures or arrays that way because it’s inefficient to be copying that data. A pointer allows you to pass the location of the data rather than the data itself, which tends to be more efficient.
A pointer also lets the function alter the data that is being pointed to, including data outside the scope of the function.
2
u/nacaclanga Jul 07 '26
"Pass by value" means that when calling a function, the values of all the parameters are writen to the parameter variables of the function. When the called function modifies them, the changes are not persistent. And similarly when the function manages to modify the variables allready passed, the parameters won't change. This is the convention used in C.
"Pass by reference" means that parameters are references to the locations of the original parameters. In particular, any changes to the parameter value are persistent after the called function exits. This is not supported in plain C, but exists in e.g. Fortran and C++.
"Pass by pointer" is a way of emulating the "pass by reference" behaviour explictily using "pass by value" in a language which supports pointers. Instead of the variable, the child function is expected to modify, you'd take its address and pass it as a pointer to the function. The function is the dereferencing the pointer as needed. This is very popular in C.
3
u/HashDefTrueFalse Jul 05 '26
I wrote an answer to this here a while ago. It's here if you're interested.
1
u/sciencekm Jul 05 '26 edited Jul 05 '26
The easiest illustration would be an integer.
To pass an integer by value, an actual number (say 123) is pushed on to the stack before the function is called. This number may be an actual constant or it may have been taken from somewhere in memory.
To pass by reference, somewhere in memory (data, heap or stack), there is number stored in that memory. The address of that memory is pushed on to the stack before the function is called.
Note that sometimes, the pushing on to the stack is instead replaced with copying to a register. In any case, the function you are calling gets either the actual number, or the address of a memory containing that number.
1
u/flatfinger Jul 07 '26
In languages that support real pass-by-reference semantics, a compiler need not accommodate the possibility that a called function might persist the address of a passed object in a place that could be used by some other function. Some such languages may also waive accommodations for the possibility that a passed reference is used to access storage that is also accessed via other means. The C99
restrictqualifier is supposed to serve the latter purpose, but its definition for 'based upon' is hand-wavy in ways that clang and gcc exploit to treat some pointers as not being based upon themselves.1
u/altaccount1232123 Jul 10 '26
Pass by value: the value of the variable is given to the function. So if you have x=10 and call func(x) then the function now has a parameter p=10. Modifying p has no effect on x.
Pass by reference: the location of the variable in memory is given to the function. The function is now able to use that location (aka pointer) to access the variable itself. So you have x=10 and call func(x), now the function has parameter p=&x. Let's say inside the function you do (*p)++, now once you are out of the function and you get the value of x you'll see that x=11. The function modified the value of the x variable by using the parameter p which points to x.
Pass by value is the basic way to do it and if you have a simple function that only takes one number and gives you one number back then you can just pass by value and return the result. But what if the function needs access to a large array? Pass by value would create a copy of the array, which would use a lot of extra memory, and creating the copy would take a long time. That's not good. You can avoid both of these problems by using pass by reference. Pass a reference to the array, have the function use the reference to edit the original array, and return simply whether the function was successful or not with a 0 or 1 (an exit code). Now your original array contains the output of the function.
This is a super common design. It's actually so common and works so well with how arrays are designed that arrays actually pass by reference by default. This is because an array is simply a pointer to the first element and the rest of the elements are located sequentially in address space. So you can treat an array like a pointer and do pointer arithmetic instead of array syntax and it does the exact same thing. You can also treat any pointer as an array and C will try to use it as such.
So when you give an array to a function, C simply sees a pointer and creates a parameter with the value of that pointer. This means you lose the context that it is an array, but as long as you define the parameter with array syntax you'll be fine and your IDE will be able to figure it out. This design is also why you need to keep track of length separately. There is no such thing as a "length" property if all the array is is a pointer to the first element. So, you need to store the length when you create the array otherwise it's lost. Then, if the function needs this length, you'll need to give the length to the function. Since it's just a single number and you're not modifying it you can use pass by value. Here is an example of a function prototype that takes an array: func(int[] arr, int arr_l); The function: func(int* arr, int arr_l); is equivalent and you are passing the exact same variables of the exact same type in both cases, except your IDE may not know that it's an array in the second case. That's about the only difference, though.
1
u/kazah-png Jul 13 '26
Valor: copia. No toca el original.
Puntero: dirección. Modifica el original. En C.
Referencia: apodo. Modifica el original. Solo en C++.
1
u/CowBoyDanIndie Jul 05 '26
By value makes a copy, if you modify it the original is not changed, the others don’t make a copy, if you modify it you are modifying the original. Pointer can be null, ref cannot without a nasty cast that is UB. Ref and pointer often work identical under the hood but are not guaranteed to.
1
u/5b49297 Jul 05 '26
A function takes arguments (values) and returns a value.* (Each value lives on the stack and exists only inside the function.) Ideally, that's all it does. Pure functions, those which rely on nothing but the arguments and change nothing, are easily tested and trivially parallelised.
Pointers are addresses of (or references to) values. They let the function change data outside its own scope. That way it can "return" multiple values without passing structs around. You know how global variables are frowned upon? That's because they're, effectively, pointers. The reason they still get used is that it's really efficient. (Until it isn't - Foot, meet Bullet.)
* Functions of type void, called procedures in other languages, don't return anything, but using pointers still allows them to change data that's passed to them. (Or global data, for that matter.) Please don't do that. At the very least return a status code.
1
u/ReallyEvilRob Jul 06 '26
C doesn't have references. Anything you would use a reference for is what you would use a pointer for.
0
u/cheesengrits69 Jul 05 '26
Pass by value gives the function a copy of the thing.
Pass by pointer is just a pass by value, where the value is a memory address. It gives the function access to the original object instead of just a copy of the original object by dereferencing the memory address of the original object which you passed to the function.
Pass by reference is the same thing as pass by pointer, except the memory address is being derived in the function call instead of being stored in a pointer first.
So the difference between:
int a = 2 + 5; f(a);
And the following:
f(2+5);
Is the same as the difference between:
int* p = &someInt; f(p); // pass by pointer
And the following:
f(&someInt); // pass by reference
0
u/Wertbon1789 Jul 05 '26
So C doesn't really have the concept of pass by reference. You'll always pass by value, it's just that passing a pointer by value enables you to implement the behavior that passing by reference would give you. One could say that passing a pointer by value is just "pass by reference" in C, but typically passing by reference implies certain guarantees which are not met by passing a pointer by value. E.g. C++ references under the hood are just pointers, but also carry more info, especially because there's no null reference in C++, so you typically wouldn't check it against NULL or similar. In Rust references also carry lifetime guarantees, so that you never run into the issue of having a stale reference somewhere.
As it often is in C, you get basically the most primitive version of concepts you can get.
0
u/GenericFoodService Jul 05 '26
Pass by value: I am giving you a copy of George. You will modify a copy.
Pass by pointer: I am telling you where George is at. You directly modify him.
Pass by reference: I am giving you George. You directly modify him. This is usually implemented as passing by pointer, but with different syntax.
-1
u/TheEdonReddit Jul 05 '26
Pass by value puts a copy on the stack to work on. Pass by reference puts a pointer to the actual data on the stack instead. The differences depends on the size of the data and what you are doing with the data in your code. It could mean zero functional difference, or it could be a huge difference. A lot of nuance for a simple concept.
-5
u/FallenDeathWarrior Jul 05 '26
Pass by value:
Creates a copy of the value. You don't modify the original value.
Pass by pointers: You hand the pointer (memory) address over. Which means you have to dereference the pointer to modify the value. You can also hand NULL over which can be a problem if not handled correctly.
Pass by reference: You hand the value over and can modify it directly. Is more "safe" the the pointer method. Can't be reassigned to a new memory adress.
https://www.geeksforgeeks.org/c/difference-between-call-by-value-and-call-by-reference/
16
u/[deleted] Jul 05 '26
[removed] — view removed comment