Call by Value:
- In call by value, a copy of the actual parameter's value is passed to the function.
- Changes made to the parameter within the function do not affect the original value outside the function.
- It's like giving someone a photocopy of a document; they can make changes to the copy, but the original remains untouched.
- Primitive data types like int, float, char, etc., are typically passed by value.
void swap(int a, int b) {
int temp = a;
a = b;
b = temp;
}
int main() {
int x = 5, y = 10;
swap(x, y);
// x and y remain unchanged after the swap function call
return 0;
}
Call by Reference:
- In call by reference, the memory address (reference) of the actual parameter is passed to the function.
- Changes made to the parameter within the function directly affect the original value outside the function.
- It's like giving someone the original document; any changes made to it will reflect wherever it's referenced.
- Pointers are typically used to achieve call by reference in C.
void swap(int *a, int *b) {
int temp = *a;
*a = *b;
*b = temp;
}
int main() {
int x = 5, y = 10;
swap(&x, &y);
// x and y have been swapped
return 0;
}