Skip to main content

Command Palette

Search for a command to run...

An application of pointers

'Returning' more than one values from a function

Updated
1 min readView as Markdown
An application of pointers

We want to write a function that calculates the area as well as the perimeter of a circle whose radius is passed as an argument to the function. No calculation should take place in main(), the calling function.

Pointers allow the programmer to ‘return’ more than one value by allowing the arguments to be passed by address, which allows the function to alter the values pointed to, and thus ‘return’ more than one value from a function.

So in this case, the radius argument is passed by value and the perimeter argument is passed by reference.

Alternatively we could also pass a third argument area by reference. Or we could create an array called result[] in main() and the function would write the area and the perimeter in result[0] and result[1] respectively.

Program:

#include <stdio.h>
 int main()
 {
 float r, area, perimeter;
 float compute(float, float *);
 printf("\nEnter the radius of the circle:");
 scanf("%f",&r);
 area=compute(r, &perimeter);
 printf("\nAREA = %f", area);
 printf("\nPERIMETER = %f", perimeter);
 return 0;
 }

float compute(float r, float *p)
 {
 float a;
 a=(float)3.1415 * r * r;
 *p=(float)3.1415 * 2 * r;
 return a;
 }

Output:

14 views

More from this blog

P

Programming Tutorials

89 posts