This code demonstrates how to use pass-by-reference in C to calculate and return multiple values from a function. Specifically, the areaPerimeter
function calculates the area and perimeter of a rectangle based on the provided length and width and updates these values in the caller’s variables by passing their memory addresses (pointers).
#include <stdio.h> // Function declaration void areaPerimeter(int length, int width, int *area, int *perimeter); int main(){ // Define local variables int myLength = 10; int myWidth = 5; int myArea = 0; int myPerimeter = 0; // Call the function by passing the length, width // and the memory address of area and perimeter variables areaPerimeter(myLength, myWidth, &myArea, &myPerimeter); // Print results printf("Area is: %d\n", myArea); printf("Perimeter is: %d\n", myPerimeter); return 0; } // Function definition void areaPerimeter(int length, int width, int *area, int *perimeter){ *area = length * width; *perimeter = 2 * (length + width); }
Explanation of Code
1. Function Declaration
void areaPerimeter(int length, int width, int *area, int *perimeter);
- The function
areaPerimeter
accepts two integers (length
andwidth
) by value, and two integer pointers (*area
and*perimeter
) by reference.
2. Main Function
int myLength = 10;
andint myWidth = 5;
define the length and width of the rectangle.int myArea = 0;
andint myPerimeter = 0;
initialize variables to store the calculated area and perimeter.- The function
areaPerimeter
is called, passingmyLength
andmyWidth
by value, while&myArea
and&myPerimeter
are passed by reference (addresses). - The function modifies
myArea
andmyPerimeter
directly via their pointers.
3. Function Definition
void areaPerimeter(int length, int width, int *area, int *perimeter)
receiveslength
andwidth
as values, whilearea
andperimeter
are pointers.*area = length * width;
calculates the area and assigns it to the memory location pointed to byarea
.*perimeter = 2 * (length + width);
calculates the perimeter and assigns it to the memory location pointed to byperimeter
.
4. Output
After the function call, myArea
and myPerimeter
contain the updated values, which are then printed.
Conclusion
This code demonstrates the importance of passing variables by reference in C when a function needs to modify multiple values and return them to the caller. This technique allows efficient memory usage and helps achieve multiple outputs without relying on return values, which is especially useful in C, where functions can only return one value directly. This approach is essential in performance-sensitive applications, as it minimizes the overhead of copying data.