Monday, April 1, 2013

The bigger2 function: using pointer arguments

This function returns nothing but will change the value of the variable in the calling function's memory area.

/* Problem: Write a void function that "returns" the largest
value of two real numbers. */

/* this function returns nothing but will
change the value of the variable in the calling
function's memory area */

void
bigger2 (double n1, double n2, double *result)
{

 if (n1>n2)
  *result = n1;
 else
  *result = n2;

/* *result in bigger2 uses the same 
memory cell as result in main */
}



int
main (void)
{
 double x, y, result;

 printf ("Enter a real number: ");
 scanf ("%lf", &x);

 printf ("Enter a real number: ");
 scanf ("%lf", &y);

 /* calling the function (3 arguments) */
 /* &result is the address where variable result is stored */
 bigger2 (x, y, &result);

 /* printing the report */
 printf ("The largest number is %f.\n", result); 

 return (0);
}

Legend: preprocessor directives | variable declarations | main program | helper functions | user-defined structures | comments
Enter a real number: 12.4
Enter a real number: 67.3
The largest number is 67.300000.

No comments:

Post a Comment