Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Explain the pointers for inter-function communication in C language.
Pointers enable inter-function communication in C by allowing functions to modify variables in the calling function's scope. This is essential for pass-by-reference behavior and returning multiple values from a single function.
Syntax
// Function declaration with pointer parameters return_type function_name(data_type *pointer_param); // Function call passing address function_name(&variable);
Key Concepts
- Pass-by-value: Function receives a copy of the variable's value
- Pass-by-reference: Function receives the address of the variable using pointers
- Multiple return values: Use pointers to modify multiple variables in the calling function
Example: Returning Multiple Values
The following program demonstrates how pointers enable a function to return multiple values by modifying variables through their addresses −
#include <stdio.h>
void areaperi(int radius, float *area, float *perimeter) {
*area = 3.14 * radius * radius;
*perimeter = 2 * 3.14 * radius;
}
int main() {
int r;
float a, p;
printf("Enter radius of circle: ");
scanf("%d", &r);
areaperi(r, &a, &p);
printf("Area = %.2f<br>", a);
printf("Perimeter = %.2f<br>", p);
return 0;
}
Enter radius of circle: 5 Area = 78.50 Perimeter = 31.40
Example: Swapping Two Numbers
This example shows how pointers allow functions to modify the original variables −
#include <stdio.h>
void swap(int *a, int *b) {
int temp = *a;
*a = *b;
*b = temp;
}
int main() {
int x = 10, y = 20;
printf("Before swap: x = %d, y = %d<br>", x, y);
swap(&x, &y);
printf("After swap: x = %d, y = %d<br>", x, y);
return 0;
}
Before swap: x = 10, y = 20 After swap: x = 20, y = 10
Key Points
- Pointers have a specific type associated with them (int*, float*, char*, etc.)
- All pointers have the same size regardless of the type they point to
- Use
&operator to get the address of a variable - Use
*operator to dereference a pointer and access the value
Conclusion
Pointers are essential for inter-function communication in C, enabling functions to modify caller variables and return multiple values. They provide the mechanism for true pass-by-reference behavior in C programming.
Advertisements
