Explanation
Pass by Value:
-
In this method, a copy of the actual parameter is passed to the function. Changes made to the parameter inside the function do not affect the original value.
-
This is the default method for passing parameters in C.
Example:
#include <stdio.h>
void modifyValue(int x) {
x = x * 2; // Changes made to x don't affect the original value
}
int main() {
int value = 5;
modifyValue(value);
printf("Original value: %d\n", value); // Output: Original value: 5
return 0;
}
Pass by Pointer:
-
In this method, a pointer to the actual parameter is passed to the function. Changes made to the parameter inside the function affect the original value.
Example:
#include <stdio.h>
void modifyValue(int *x) {
*x = *x * 2; // Changes made to *x affect the original value
}
int main() {
int value = 5;
modifyValue(&value);
printf("Original value: %d\n", value); // Output: Original value: 10
return 0;
}
Pass by Reference (Not Native to C, Simulated Using Pointers):
-
C doesn't have true pass-by-reference, but you can simulate it by passing a pointer to a variable.
-
This allows changes made to the parameter inside the function to affect the original value.
Example:
#include <stdio.h>
void modifyValue(int &x) { // Simulated pass-by-reference
x = x * 2;
}
int main() {
int value = 5;
modifyValue(value);
printf("Original value: %d\n", value); // Output: Original value: 10
return 0;
}