woensdag 20 juni 2007

Multiple Arguments to functions

A function can have more than one argument. In the function call, you separate the arguments with commas:

n_chars('R', 25);

This passes two arguments to the function n_chars().

Similarly, when you define the function, you use a comma-seperated list of parameter declarations in the function header:

void n_chars(char c, int n) // two arguments

This function header states that the function n_chars() takes one type char argument and one type int argument. The parameters c and n are assigned the values passed to the function.
If a function has two parameters of the same type, you have to give the type of each parameter seperately.

void fifi(float a, float b) // declare each variable separately
void fufu(float a, b) // NOT acceptable

As with other functions, you just add a semicolon to get a prototype

void n_chars(char c, int n); // prototype, style 1

void n_chars(char, int); // prototype style 2

However, providing variable names can make the prototype more understandable, particularly if two parameters are the same type. Then, the names can remind you which argument is which:

double melon_density(double weight, double volume);

Geen opmerkingen: