Creating Functions That Take Arguments

The next logical evolution of your user-defined functions is to have them take arguments. Most C functions take arguments, like isalpha(), which expects a character to be passed to it. To have your functions take arguments, you need to define them—both in the prototype and in the formal definition—with the type of arguments expected:

void my_func (int age, int year);
int main (void) {
   // Call my_func().
}
void my_func (int age, int year) { ...

When calling a function that takes arguments, you need to then pass it the appropriate values. As you've already seen, there are many ways of doing this, from passing literal values to variable values to the results of calculations. Each of these function calls are valid:

int my_var = 100;
my_func (my_var, 8);
my_func (my_var * 2, my_var + 1);

It's important to remember that the values passed to the function must be of the right type and order. In other words, the first value passed to a function will be assigned to the function's first argument variable and the second to the second. There's no way to pass a value to the second function argument without passing one to the first.

In our next example, the ability to display a list of currency conversions will be turned into its own function. This function will take two arguments: the exchange rate and the column title (e.g., Euro or Peso).

To define and use functions that take arguments

1.
Create a new file or project in your text editor or IDE.

2.
Type the standard beginning lines of code (Script 7.2):

/* exchange_function.c - Script 7.2
 */
#include <stdio.h>

Script 7.2. The make_exchange_table() function takes two arguments—a conversion rate and a column heading—and creates a list of currency conversions.


3.
Add the function prototype:

void make_exchange_table(float rate,
 char title[]);

The function being defined in this file is called make_exchange_table. It's a long name, but descriptive. This function takes two arguments. The first will be a float, and the second will be a character array. When passing arrays of any type to your function, do not include their dimension (the number of elements in the array) in the definition. In other words, prototype the function with array_name[] instead of array_name[6] or array_name[600].

4.
Begin the main function:

int main (void) {

5.
Call the make_exchange_table() function:

make_exchange_table (11.317466,
 "Pesos");

This first call will convert dollars to pesos. The two proper arguments are passed to the function. The first is a float, corresponding to the conversion rate. This will be assigned to the rate variable within the make_exchange_table() function.

The second argument will be used for the column heading in the displayed table (Figure 7.2).

Figure 7.2. The make_exchange_table() function uses the second argument it receives as the column heading for the table.


6.
Make another call to the function, using different values:

make_exchange_table (0.823859,
 "Euros");

This step calls the same function again, passing different parameters, which will generate different results (see the bottom table in Figure 7.2).

7.
Complete the main function:

    getchar();
    return 0;
}

8.
After the main function, begin defining the make_exchange_table() function:

void make_exchange_table(float rate,
 char title[]) {

As the prototype indicates, this function takes two arguments: a float and a character string. With the first function call (Step 5), 11.317466 is assigned to rate and Pesos to title. In the second function call (Step 6), rate and title are 0.823859 and Euros, respectively.

9.
Define the required variable:

float i;

This function will make use of a loop, which therefore requires a counter variable, called i. The other two variables used by the function have already been declared in the function definition.

10.
Print a table heading:

printf ("%10s %10s
", "Dollars",
 title);

Like the similar examples in previous chapters, this application creates a spaced-out header. The heading for the second column comes from the passed title value.

11.
Define the loop:

for (i = 10.00; i <= 100.00; i +=
 10.00) {

This loop will iterate from 10.00 to 100.00 in $10 increments.

12.
Print each dollar amount and the respective conversion:

printf ("%10.2f %10.2f
", i, i *
 rate);

This line will print the original value of i, representing U.S. dollars, along with the value of i times the conversion rate. This second calculated number will represent the other currency value.

13.
Complete the function definition:

    }
    printf ("

");
}

The first curly brace closes the for loop. Then, two blank lines are printed for a better appearance in the standard output. Finally, the function itself is closed.

14.
Save the file as exchange_function.c, compile, and debug as necessary.

15.
Run the application (Figure 7.2).

16.
If desired, change the function call lines, recompile, and run the application again (Figure 7.3).

Figure 7.3. Changing the function call lines creates different conversion tables.


✓ Tips

  • You can even pass values to a function by calling a separate function and using its returned value as the argument. In this example, the sscanf() function will return the number of items it read in, which will be an integer passed to

    my_func():
    my_func (4, sscanf ("%s", input));
    
  • If your function takes several arguments of the same type, you cannot use the variable declaration shortcut of separating each by a comma. This is invalid:

    void function_name (int num1,
     num2) { ...
    

    This is valid:

    void function_name (int num1, int
     num2) {...
    
  • You cannot set default values for function arguments in C.

  • The make_exchange_table() function could be altered to take a third parameter, indicating the dollar increments you want to use or the dollar range (Figure 7.4):

    void make_exchange_table(float rate,
     char title[], float limit);
    

    Figure 7.4. Minor modifications to the function definition can make it easy to generate different results. Here, the upper limit for each conversion is sent as an argument.

  • You aren't required to include the variable name in a function's prototype (just its type), but it's a good idea.

  • C99 technically calls variables in the function definition parameters; arguments are passed to the function when it's called.


..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset