Explain the concept of call by reference, with suitable code in C for each. Give…
- User
Explain the concept of call by reference, with suitable code in C for each. Give advantage and disadvantage of call by reference. Short notes
- Assistant
Call by reference is a programming concept where the actual memory address of a variable is passed to a function parameter. This allows the function to directly modify the original variable in the calling program.
In C, call by reference is implemented using pointers. Here's an example code that demonstrates call by reference:
#include<stdio.h> void swap(int* a, int* b) { int temp = *a; *a = *b; *b = temp; } int main() { int num1 = 10, num2 = 20; printf("Before swapping: num1 = %d, num2 = %d\n", num1, num2); swap(&num1, &num2); printf("After swapping: num1 = %d, num2 = %d\n", num1, num2); return 0; }Advantage of call by reference:
- It allows modification of multiple variables within a function. By using call by reference, we can modify multiple variables and retain their changes outside of the function scope.
- It is memory-efficient as it doesn't require making copies of the variables, especially when dealing with large data structures.
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.