08.01.2023 Views

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

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Chapter 7 ■ Functions

• The logic for calculating the factorial is the same for both program and function.

• The program prints the answer (in nfac); the function returns the answer (in

nfac) to the calling function. The answer is returned to the point at which

factorial was called.

Other comments on factorial

• Variables declared within a function are said to be local to the function.

Thus, nfac is a local variable, used to hold the factorial. As a matter of

interest, h is local to the for statement. When factorial is called, storage is

allocated to nfac and h. These variables are used to work out the factorial.

Just before the function returns, nfac and h are discarded.

• You should verify that the function works properly if n is 0 or 1 (that is, it

returns 1).

We now take a detailed look at what happens when factorial is called (from main, say).

Consider the statements (m and fac are int):

m = 3;

fac = factorial(m);

The second statement is executed as follows:

• The value of the argument m is determined; it is 3.

• This value is copied to a temporary memory location and this location is passed

to the function. The function labels it with the name of the parameter, n. The

net effect is as if execution of the function began with the statement

n = 3;

• In programming terminology, we say that the argument m is passed “by

value.” The value of the argument is copied to a temporary location, and it is

this temporary location that is passed to the function. The function has no

access whatsoever to the original argument. In this example, factorial has

no access to m and, hence, cannot affect it in any way.

• After n is assigned the value 3, execution of factorial proceeds as described

above. Just before the function returns, the storage location occupied by n

is discarded. In effect, the parameter n is treated like a local variable except

that it is initialized to the value of the argument supplied.

• The value returned by the function is the last value stored in nfac. In this

example, the last value assigned to nfac is 6. Therefore, the value 6 is

returned to the place from which the call factorial(3) was made.

• The value 6 returned by factorial is assigned to fac.

• Execution continues with the next statement, if any.

180

www.it-ebooks.info

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

Saved successfully!

Ooh no, something went wrong!