08.01.2023 Views

Learn to Program with C_ Learn to Program using the Popular C Programming Language ( PDFDrive )

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Chapter 7 ■ Functions

The function header is followed by the left brace of the body.

Parameters are specified in the same way variables are declared. In fact, they really are

declarations. The following are all valid examples of headers of void functions:

void sample1(int m, int n)

// 2 parameters

void sample2(double a, int n, char c)

// 3 parameters

void sample3(double a, double b, int j, int k) // 4 parameters

Each parameter must be declared individually and two consecutive declarations are

separated by a comma. For example, it is invalid to write

void sample1(int m, n) //not valid; must write (int m, int n)

Shortly, we will see examples of functions that return a value.

7.3.2 How a Function Gets Its Data

A function is like a mini program. In the programs we have written, we have stated what data

must be supplied to the program, what processing must take place, and what the output (results)

should be. We must do the same when we write a function.

When we write a function header, we use the parameter list to specify what data must be

supplied to the function when it is called. The list specifies how many data items, the type of the

each item, and the order in which they must be supplied.

For example, we wrote skipLines with an integer parameter n; this says that an integer value

must be supplied to skipLines when it is called. When skipLines is called, the argument supplied

becomes the specific value of n and the function is executed assuming that n has this value. In the

call skipLines(3), the argument 3 is the data that skipLines needs to perform its job.

It is worth emphasizing that main gets its data by using scanf, among other functions, to read

and store the data in variables. On the other hand, a function gets its data when it is called. The

variables in the parameter list are set to the values of the corresponding arguments used in the

call. For example, when we write the header

void sample(int n, char c, double b)

we are saying that, when we call sample, we must do so with three arguments: the first must be an

int value, the second a char value and the third a double value.

Assuming that num is int, ch is char and x is double, the following are all valid calls to sample:

sample(25, 'T', 7.5);

sample(num, 'A', x);

sample(num, ch, 7); //an int argument can match a double parameter

sample(num + 1, ch, x / 2.0);

169

www.it-ebooks.info

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!