Build Menu

Chapter 8 - Writing and Using Functions

Visual C++ 6: The Complete Reference
Chris H. Pappas and William H. Murray, III
  Copyright 1998 The McGraw-Hill Companies

Function Arguments
This section discusses how to pass function arguments to a function. These arguments go by many different names. Some programmers call them arguments, while others refer to them as parameters or dummy variables.
Function arguments are optional. Some functions you design may receive no arguments, while others may receive many. Function argument types can be mixed; that is, you can use any of the standard data types as a function argument. Many of the following examples illustrate passing various data types to functions. Furthermore, these programs employ functions from the various C and C++ libraries. Additional details on these library functions and their prototypes can be found in the Visual C/C++ reference manuals.
Actual vs. Formal Parameters
Each function definition contains an argument list, called the formal argument list. Items in the list are optional, so the actual list may be empty or it may contain any combination of data types, such as integer, float, and character.
When the function is called by the program, an argument list is also passed to the function. This list is called the actual argument list. In general, there is usually a 1:1 match, when writing ANSI C code, between the formal and actual argument lists, although in reality no strong enforcement is used.
Examine the following line of C code:
printf(“This is hexadecimal %x and octal %o”,ians);
In this situation, only one argument is being passed to printf( ), although two are expected. When fewer arguments are supplied, the missing arguments are initialized to meaningless values. C++ overcomes this problem, to a degree, by permitting a default value to be supplied with the formal argument list. When an argument is missing in the actual argument list, the default argument is automatically substituted. For example, in C++, the function prototype might appear as
int iyourfunction(int it,float fu=4.2,int iv=10)
Notice, if either fu or iv is not specified in the call to the function iyourfunction( ), the values shown (4.2 or 10) will be used. C++ requires that all formal arguments using default values be listed at the end of the formal argument list. In other words, iyourfunction(10) and iyourfunction(10,15.2) are valid. If fu is not supplied, iv cannot be supplied either.
void Parameters
In ANSI C, void should be used to explicitly state the absence of function arguments. In C++, the use of void is not yet required, but its use is considered wise. The following program has a simple function named voutput( ) that receives no arguments and does not return a value. The main( ) function calls the function voutput( ). When the voutput( ) function is finished, control is returned to the main( ) function. This is one of the simplest types of functions you can write.
/*
*   fvoid.c
*   A C program that will print a message with a function.
*   Function uses a type void argument and sqrt function
*   from the standard C library.
*   Copyright (c) Chris H. Pappas and William H. Murray, 1998
*/

#include <stdio.h>
#include <math.h>

void voutput(void);
int main()
{
 printf(“This program will find the square root. \n\n”);
 voutput();

 return (0);
}

void voutput(void)
{
 double dt=12345.0;
 double du;

 du=sqrt(dt);
 printf(“The square root of %lf is %lf  \n”,dt,du);
}
As you study the example, notice that the voutput( ) function calls a C library function named sqrt( ). The prototype for the sqrt( ) library function is contained in MATH.H. It accepts a double as an argument and returns the square root as a double value.
char Parameters
Character information can also be passed to a function. In the next example, a single character is intercepted from the keyboard, in the function main( ), and passed to the function voutput( ). The getch( ) function reads the character. There are other functions that are closely related to getch( ) in the standard C library: getc( ), getchar( ), and getche( ). These functions can also be used in C++, but in many cases a better choice will probably be cin. Additional details for using getch( ) are contained in your Visual C/C++ reference manuals and are available as online help. The getch( ) function intercepts a character from the standard input device (keyboard) and returns a character value, without echo to the screen, as shown here:
/*
*   fchar.c
*   C program will accept a character from keyboard,
*   pass it to a function and print a message using
*   the character.
*   Copyright (c) Chris H. Pappas and William H. Murray, 1998
*/

#include <stdio.h>

void voutput(char c);

int main()
{
 char cyourchar;

 printf(“Enter one character from the keyboard. \n”);
 cyourchar=getch();
 output(cyourchar);

 return (0);
}

void voutput(char c)
{
 int j;

 for(j=0;j<16;j++)
   printf(“The character typed is %c  \n”,c);
}
Notice, in the previous listing, that a single character is passed to the function. The function then prints a message and the character 16 times. The %c in the printf( ) function specifies that a single character is to be printed.
int Parameters
In the following application, a single integer will be read from the keyboard with C’s scanf( ) function. That integer will be passed to the function vside( ). The vside( ) function uses the supplied length to calculate and print the area of a square, the volume of a cube, and the surface area of a cube.
/*
*   fint.c
*   C program will calculate values given a length.
*   Function uses a type int argument, accepts length
*   from keyboard with scanf function.
*   Copyright (c) Chris H. Pappas and William H. Murray, 1998
*/

#include <stdio.h>

void vside(int is);

int main()
{
 int iyourlength;

 printf(“Enter the length, as an integer,\n”);
 printf(“from the keyboard. \n”);
 scanf(“%d”,&iyourlength);
 vside(iyourlength);
 return (0);
}

void vside(int is)
{
 int iarea,ivolume,isarea;

 iarea=is
*is;
 ivolume=is
*is*is;
 isarea=6
*area;

 printf(“The length of a side is %d  \n\n”,is);
 printf(“A square would have an area of %d \n”,iarea);
 printf(“A cube would have a volume of %d \n”,ivolume);
 printf(“The surface area of the cube is %d \n”,isarea);
}
Note that the variable is and all calculated values are integers. What would happen if is represented the radius of a circle and sphere to the calculated types?
float Parameters
Floats can also be passed as arguments to a function. In the following example, two floating-point values are passed to a function called vhypotenuse( ). The scanf( ) function is used to intercept both float values from the keyboard.
/*
*   ffloat.c
*   C program will find hypotenuse of a right triangle.
*   Function uses a type float argument and accepts
*   input from the keyboard with the scanf function.
*   Copyright (c) Chris H. Pappas and William H. Murray, 1998
*/

#include <stdio.h>
#include <math.h>

void vhypotenuse(float fx,float fy);

int main()
{
 float fxlen,fylen;

 printf(“Enter the base of the right triangle. \n”);
 scanf(“%f”,&fxlen);
 printf(“Enter the height of the right triangle. \n”);
 scanf(“%f”,&fylen);
 vhypotenuse(fxlen,fylen);

 return (0);
}

void vhypotenuse(float ft,float fu)
{
 double dresult;
 dresult=hypot((double) ft,(double) fu);
 printf(“The hypotenuse of the right triangle is %g \n”,
        dresult);
}
Observe that both arguments received by vhypotenuse( ) are cast to doubles when used by the hypot( ) function from MATH.H. All MATH.H functions accept and return double types. Your programs can use the additional math functions listed in Table 8-1.
You can also display the contents of your MATH.H header file for additional details.
Table 8-1: Macro and Function Prototyoes Provided by MATH.H
double _hypot(double, double);
double _cabs(struct _complex);
double _j1(double);
double _j0(double);
double _y0(double);
double _jn(int, double);
double _yn(int, double);
double _y1(double);
double asin(double);
double acos(double);
double atan2(double, double);
double atan(double);
double cabs(struct _complex);
double atof(const char *);
double cos(double);
double ceil(double);
double exp(double);
double cosh(double);
double floor(double);
double fabs(double);
double frexp(double, int *);
double fmod(double, double);
double j0(double);
double hypot(double, double);
double jn(int, double);
double j1(double);
double log(double);
double ldexp(double, int);
double modf(double, double *);
double log10(double);
double sin(double);
double pow(double, double);
double sqrt(double);
double sinh(double);
double tanh(double);
double tan(double);
double y1(double);
double y0(double);
double abs(double _X)
double yn(int, double);
double pow(int _X, int _Y)
double pow(double _X, int _Y)
float acosf(float);
float asinf(float);
float atan2f(float, float);
float atanf(float);
float ceilf(float);
float cosf(float);
float coshf(float);
float expf(float);
float fabsf(float);
float floorf(float);
float fmodf(float, float);
float hypotf(float, float);
float log10f(float);
float logf(float);
float modff(float, float*);
float powf(float, float);
float sinf(float);
float sinhf(float);
float sqrtf(float);
float tanf(float);
float tanhf(float);
float abs(float _X)
float acos(float _X)
float asin(float _X)
float atan(float _X)
float atan2(float _Y, float _X)
float ceil(float _X)
float cos(float _X)
float cosh(float _X)
float exp(float _X)
float fabs(float _X)
float floor(float _X)
float fmod(float _X, float _Y)
float frexp(float _X, int * _Y)
float ldexp(float _X, int _Y)
float log(float _X)
float log10(float _X)
float modf(float _X, float * _Y)
float pow(float _X, float _Y)
float pow(float _X, int _Y)
float sin(float _X)
float sinh(float _X)
float sqrt(float _X)
float tan(float _X)
float tanh(float _X)
float acosf(float _X)
float asinf(float _X)
float atan2f(float _X, float _Y)
float atanf(float _X)
float ceilf(float _X)
float cosf(float _X)
float coshf(float _X)
float expf(float _X)
float fabsf(float _X)
float floorf(float _X)
float fmodf(float _X, float _Y)
float frexpf(float _X, int *_Y)
float ldexpf(float _X, int _Y)
float log10f(float _X)
float logf(float _X)
float modff(float _X, float *_Y)
float powf(float _X, float _Y)
float sinf(float _X)
float sinhf(float _X)
float sqrtf(float _X)
float tanf(float _X)
float tanhf(float _X)
long abs(long _X)
long double _atold(const char *);
long double _cabsl(struct _complexl);
long double _hypotl(long double,
long double);
long double _j0l(long double);
long double _j1l(long double);
long double _jnl(int, long double);
long double _y0l(long double);
long double _y1l(long double);
long double _ynl(int, long double);
long double acosl(long double);
long double asinl(long double);
long double atan2l(long double,
long double);
long double atanl(long double);
long double ceill(long double);
long double coshl(long double);
long double cosl(long double);
long double expl(long double);
long double fabsl(long double);
long double floorl(long double);
long double fmodl(long double,
long double);
long double frexpl(long double, int *);
long double ldexpl(long double, int);
long double log10l(long double);
long double logl(long double);
long double modfl(long double,
long double *);
long double powl(long double,
long double);
long double sinhl(long double);
long double sinl(long double);
long double sqrtl(long double);
long double tanhl(long double);
long double tanl(long double);
long double abs(long double _X)
long double acos(long double _X)
long double asin(long double _X)
long double atan(long double _X)
long double atan2(long double _Y,
long double _X)
long double ceil(long double _X)
long double cos(long double _X)
long double cosh(long double _X)
long double exp(long double _X)
long double fabs(long double _X)
long double floor(long double _X)
long double fmod(long double _X,
long double _Y)
long double frexp(long double _X,
int * _Y)
long double ldexp(long double _X,
int _Y)
long double log(long double _X)
long double log10(long double _X)
long double modf(long double _X,
long double * _Y)
long double pow(long double _X,
int _Y)
long double pow(long double _X,
long double _Y)
long double sin(long double _X)
long double sinh(long double _X)
long double sqrt(long double _X)
long double tan(long double _X)
long double tanh(long double _X)
long double acosl(long double _X)
long double asinl(long double _X)
long double atan2l(long double _X,
long double _Y)
long double atanl(long double _X)
long double ceill(long double _X)
long double coshl(long double _X)
long double cosl(long double _X)
long double expl(long double _X)
long double fabsl(long double _X)
long double floorl(long double _X)
long double fmodl(long double _X,
long double _Y)
long double frexpl(long double _X,
int *_Y)
long double ldexpl(long double _X,
int _Y)
long double log10l(long double _X)
long double logl(long double _X)
long double modfl(long double _X,
long double *_Y)
long double powl(long double _X, long double _Y)
long double sinhl(long double _X)
long double sinl(long double _X)
long double sqrtl(long double _X)
long double tanhl(long double _X)
long double tanl(long double _X)
double Parameters
The double type is a very precise float value. All MATH.H functions accept and return double types. The next program accepts two double values from the keyboard. The function named vpower( ) will raise the first number to the power specified by the second number. Since both values are of type double, you can calculate 45.7 and find that it equals 428,118,741.757.
/*
*   fdoubl.c
*   C program will raise a number to a power.
*   Function uses a type double argument and the pow function.
*   Copyright (c) Chris H. Pappas and William H. Murray, 1998
*/

#include <stdio.h>
#include <math.h>

void vpower(double dt,double du);

int main()
{
 double dtnum,dunum;

 printf(“Enter the base number. \n”);
 scanf(“%lf”,&dtnum);
 printf(“Enter the power. \n”);
 scanf(“%lf”,&dunum);
 vpower(dtnum,dunum);

 return (0);
}

void vpower(double dt,double du)
{
 double danswer;

 danswer=pow(dt,du);
 printf(“The result is %lf \n”,answer);
}
This function uses the library function pow( ) to raise one number to a power, prototyped in MATH.H.
Array Parameters
The next application shows how the contents of an array are passed to a function as a call-by-reference. In this example, the address of the first array element is passed via a pointer.
/*
*   fpntr.c
*   C program will call a function with an array.
*   Function uses a pointer to pass array information.
*   Copyright (c) Chris H. Pappas and William H. Murray, 1998
*/

#include <stdio.h>

void voutput(int
*pinums);

int main()
{
 int iyourarray[7]={2,7,15,32,45,3,1};

 printf(“Send array information to function. \n”);
 voutput(iyourarray);

 return (0);
}

void voutput(int
*pinums)
{
 int t;

 for(t=0;t<7;t++)
   printf(“The result is %d \n”,pinums[t]);
}
When the function is called, only the name iyourarray is specified. In Chapter 9, you will learn more details concerning arrays. In this example, by specifying the name of the array, you are providing the address of the first element in the array. Since iyourarray is an array of integers, it is possible to pass the array by specifying a pointer of the element type.
It is also permissible to pass the address information by using an unsized array. The next example shows how you can do this in C++. (The same approach can be used in C.) The information in iyourarray is transferred by passing the address of the first element.
//
//  farray.cpp
//  C++ program will call a function with an array.
//  Function passes array information, and calculates
//  the average of the numbers.
//  Copyright (c) Chris H. Pappas and William H. Murray, 1998
//

#include <iostream.h>

void avg(float fnums[]);

int main()
{
 float iyourarray[8]={12.3,25.7,82.1,6.0,7.01,
                     0.25,4.2,6.28};
 cout << “Send information to averaging function. \n”;
 avg(iyourarray);

 return (0);
}

void avg(float fnums[])
{
 int iv;
 float fsum=0.0;
 float faverage;

 for(iv=0;iv<8;iv++) {
   fsum+=fnums[iv];
   cout << “number ” << iv+1 << “ is ” << fnums[iv] << endl;
 }
 faverage=fsum/iv;
 cout << “\nThe average is ” << faverage << endl;
}
The average is determined by summing each of the terms together and dividing by the total number of terms. The cout stream is used to format the output to the screen.

Books24x7.com, Inc 2000 –  


Visual C++ 6(c) The Complete Reference
Visual Studio 6: The Complete Reference
ISBN: B00007FYGA
EAN: N/A
Year: 1998
Pages: 207

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net