In C language there are 2 ways to pass arguments to functions, right? One of them is Pass by address. Do you not need to always pass a pointer?
I haven’t tried anything yet just wanted to know its logic/theory. I want to understand.
Zel is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
3
All C parameters are “pass by value”
void fn (int i)
{
/* You can change i in here but it's only working on a local copy of i
*/
}
void fn2(int* ip)
{
/* You can change ip in here but it's only working on a local copy of ip.
* If you change *ip then that will "stick" outside this function.
*/
}
/* sample calls */
int i=32;
fn(i);
fn2(&i);
There are two primary ways to pass arguments to functions:
Pass By Value: A copy of the argument’s value is passed to the function. Changes made within the function don’t affect the original variable. This is the default method in C and is simple but can be inefficient for large data structures since a full copy is made.
Use pass by value when you only need to read the argument’s value without modifying the original variable.
void func1_swap(int x, int y) {
int temp = x;
x=y;
y= temp;
}
Pass By Reference: The memory reference of the argument is passed to the function using a pointer. This allows the function to modify the original variable directly and is more efficient for large data structures because only the address is passed. However, it requires careful handling to avoid unintended side effects.
Use pass by address/reference (pointers) when you need to modify the original variable or handle large data structures efficiently.
void func2_swap(int *x, int *y) {
int temp = *x;
*x=*y;
*y= temp;
}
if a=10, b=20
when you call func1_swap(a,b), it will swap a value and b value internally, but original variables won’t effect
when you call func2_swap(&a,&b), it will swap a value and b value internally, but original variables also will be swapped.
2