PSP Co3
PSP Co3
1. How do you pass data to a function? Explain the concept of call by value and call
by reference through suitable examples.
In C programming, data can be passed to a function in two ways: call by value and call by
reference. Let's explore these concepts with suitable examples:
1. Call by Value:
In call by value, a copy of the value of the argument is passed to the function. Any
modifications made to the parameter within the function do not affect the original argument.
Example:
```c
#include <stdio.h>
int main() {
int num = 5;
printf("Before calling the function: %d\n", num);
increment(num);
printf("After calling the function: %d\n", num);
return 0;
}
```
Output:
```
Before calling the function: 5
Inside the function: 6
After calling the function: 5
```
Explanation: In this example, the function `increment` takes an argument `num` by value.
When the function is called, the value of `num` is copied to the parameter `num` inside the
function. Any changes made to the parameter `num` are local to the function and do not
affect the original `num` variable in the `main` function.
2. Call by Reference:
In call by reference, the memory address of the argument is passed to the function.
Modifications made to the parameter within the function affect the original argument.
Example:
```c
#include <stdio.h>
int main() {
int num = 5;
printf("Before calling the function: %d\n", num);
increment(&num);
printf("After calling the function: %d\n", num);
return 0;
}
```
Output:
```
Before calling the function: 5
Inside the function: 6
After calling the function: 6
```
Explanation: In this example, the function `increment` takes a pointer to an integer as an
argument. The address of the `num` variable is passed using the `&` operator. Inside the
function, the parameter `ptr` is a pointer that holds the memory address of `num`. By
dereferencing the pointer `ptr` using `*ptr`, we can modify the value stored at that memory
location. As a result, the changes made to `*ptr` (which is `num`) affect the original `num`
variable in the `main` function.
Call by value is useful when you want to manipulate a local copy of the data without
affecting the original, while call by reference allows you to modify the original data directly.
Understanding these concepts helps in choosing the appropriate method for passing data to
functions based on the desired behavior and requirements of your program.