Sams Teach Yourself C in 24 Hours (41 page)

BOOK: Sams Teach Yourself C in 24 Hours
2.72Mb size Format: txt, pdf, ePub

}

return 0;

}

4. Rewrite the add_two() function in Listing 14.3 to print out the previous result of the addition, as well as the counter value.

14

18 067231861x CH14 4.10.2000 11:03 AM Page 240

19 067231861x pt 4 1/25/00 10:27 AM Page 241

PART IV

Functions and Dynamic

Memory Allocation

Hour

15 Working with Functions

16 Applying Pointers

17 Allocating Memory

18 Using Special Data Types and Functions

19 067231861x pt 4 1/25/00 10:27 AM Page 242

20 067231861x CH15 4.10.2000 11:03 AM Page 243

HOUR 15

Working with Functions

Form follows function.

—L. H. Sullivan

In Hour 14, “Understanding Scope and Storage Classes,” you might have

noticed that a function definition is always given first, before the function is called from a main() function. In fact, you can put a function definition anywhere you want, as long as you put the function declaration before the first place where the function is called. You’ll learn about many features of functions from the following topics covered in this lesson:

• Function declarations

• Prototyping

• Values returned from functions

• Arguments to functions

• Structured programming

In addition, several C library functions and macros, such as time(),

localtime(), asctime(), va_start(), va_arg(), and va_end() are

introduced in this hour.

20 067231861x CH15 4.10.2000 11:03 AM Page 244

244

Hour 15

Declaring Functions

As you know, you have to declare or define a variable before you can use it. This is also true for functions. In C, you have to declare or define a function before you can call it.

Declaration Versus Definition

According to the ANSI standard, the
declaration
of a variable or function specifies the interpretation and attributes of a set of identifiers. The
definition
, on the other hand, requires the C compiler to reserve storage for a variable or function named by an identifier.

A variable declaration is a definition, but a function declaration is not. A function declaration alludes to a function that is defined elsewhere and specifies what kind of value is returned by the function. A function definition defines what the function does, as well as gives the number and type of arguments passed to the function.

A function declaration is not a function definition. If a function definition is placed in your source file before the function is first called, you don’t need to make the function declaration. Otherwise, the declaration of a function must be made before the function is invoked.

For example, I’ve used the printf() function in almost every sample program in this book. Each time, I had to include a header file, stdio.h, because the header file contains the declaration of printf(), which indicates to the compiler the return type and prototype of the function. The definition of the printf() function is placed somewhere else.

In C, the definition of this function is saved in a library file that is invoked during the linking states.

Specifying Return Types

A function can be declared to return any data type, except an array or function. The return statement used in a function definition returns a single value whose type should match the one declared in the function declaration.

By default, the return type of a function is int, if no explicit data type is specified for the function. A data type specifier is placed prior to the name of a function like this: data_type_specifier

function_name();

Here data_type_specifier specifies the data type that the function should return.

function_name is the function name that should follow the rules of naming identifiers in C.

In fact, this declaration form represents the traditional function declaration form before the ANSI standard was created. After setting up the ANSI standard, the function prototype is added to the function declaration.

20 067231861x CH15 4.10.2000 11:03 AM Page 245

Working with Functions

245

Using Prototypes

Before the ANSI standard was created, a function declaration only included the return
15

type of the function. With the ANSI standard, the number and types of arguments passed to a function can be added into the function declaration. The number and types of an argument are called the
function prototype
.

The general form of a function declaration, including its prototype, is as follows: data_type_specifier function_name(

data_type_specifier argument_name1,

data_type_specifier argument_name2,

data_type_specifier argument_name3,

.

.

.

data_type_specifier argument_nameN,

);

The purpose of using a function prototype is to help the compiler check whether the data types of arguments passed to a function match what the function expects. The compiler issues an error message if the data types do not match.

Although argument names, such as argument_name1, argument_name2, and so on, are optional, it is recommended that you include them so that the compiler can identify any mismatches of argument names.

Making Function Calls

As shown in Figure 15.1, when a function call is made, the program execution jumps to the function and finishes the task assigned to the function. Then the program execution resumes after the called function returns.

A
function call
is an expression that can be used as a single statement or within other statements.

Listing 15.1 gives an example of declaring and defining functions, as well as making function calls.

TYPE

LISTING 15.1

Calling Functions After They Are Declared and Defined

1: /* 15L01.c: Making function calls */

2: #include

3:

4: int function_1(int x, int y);

5: double function_2(double x, double y)

6: {

7: printf(“Within function_2.\n”);

continues

20 067231861x CH15 4.10.2000 11:03 AM Page 246

246

Hour 15

LISTING 15.1

continued

8: return (x - y);

9: }

10:

11: main()

12: {

13: int x1 = 80;

14: int y1 = 10;

15: double x2 = 100.123456;

16: double y2 = 10.123456;

17:

18: printf(“Pass function_1 %d and %d.\n”, x1, y1);

19: printf(“function_1 returns %d.\n”, function_1(x1, y1));

20: printf(“Pass function_2 %f and %f.\n”, x2, y2);

21: printf(“function_2 returns %f.\n”, function_2(x2, y2));

22: return 0;

23: }

24: /* function_1() definition */

25: int function_1(int x, int y)

26: {

27: printf(“Within function_1.\n”);

28: return (x + y);

29: }

FIGURE 15.1

Program execution

Start

jumps to an invoked

function when a func-

tion call is made.

Function

Call

Program Execution Flow

Function

Execution

Function

Return

End

20 067231861x CH15 4.10.2000 11:03 AM Page 247

Working with Functions

247

The following output is displayed after the executable (15L01.exe) of the program in Listing 15.1 is created and run:

15

Pass function_1 80 and 10.

OUTPUT
Within function_1.

function_1 returns 90.

Pass function_2 100.123456. and 10.123456.

Within function_2.

function_2 returns 90.000000.

The purpose of the program in Listing 15.1 is to show you how to declare and
ANALYSIS
define functions. The statement in line 4 is a function declaration with a prototype. The declaration alludes to the function_1 defined later in Listing 15.1. The return type of function_1 is int, and the function prototype includes two int variables, called x and y.

In lines 5–9, the second function, function_2, is defined before it is called. As you can see, the return type of function_2 is double, and two double variables are passed to the function. Note that the names of the two variables are also x and y. Don’t worry because function_1 and function_2 share the same argument names. There is no conflict because these arguments are in different function blocks and arguments to functions have block scope.

Then, in the main() function defined in lines 11–23, two int variables, x1 and y1, and two double variables, x2 and y2, are declared and initialized in lines 13–16, respectively.

The statement in line 18 shows the values of x1 and y1 that are passed to the function_1

function. Line 19 calls function_1 and displays the return value from function_1.

Likewise, lines 20 and 21 print out the values of x2 and y2 that are passed to function_2, as well as the value returned by function_2 after the function is called and executed.

Lines 25–29 contain the definition of the function_1 function, specifying that the function can perform an addition of two integer variables (see line 28) and print out the string of Within function_1. in line 27.

Prototyping Functions

In the following subsections, you’re going to study three cases regarding arguments passed to functions. The first case is that functions take no argument; the second one is that functions take a fixed number of arguments; the third case is that functions take a variable number of arguments.

20 067231861x CH15 4.10.2000 11:03 AM Page 248

248

Hour 15

Functions with No Arguments

The first case is a function that takes no argument. For instance, the C library function getchar() does not need any arguments. It can be used in a program like this: int c;

c = getchar();

As you can see, the second statement is left blank between the parentheses (( and )) when the function is called.

In C, the declaration of the getchar() function can be something like this: int getchar(void);

Note that the keyword void is used in the declaration to indicate to the compiler that no argument is needed by this function. The compiler will issue an error message if there is any argument passed to getchar() later in a program when this function is called.

Therefore, for a function with no argument, the void data type is used as the prototype in the function declaration.

The program in Listing 5.2 shows another example of using void in function declarations.

TYPE

LISTING 15.2

Using void in Function Declarations

1: /* 15L02.c: Functions with no arguments */

2: #include

3: #include

4:

5: void GetDateTime(void);

6:

7: main()

8: {

9: printf(“Before the GetDateTime() function is called.\n”);

10: GetDateTime();

11: printf(“After the GetDateTime() function is called.\n”);

12: return 0;

13: }

14: /* GetDateTime() definition */

15: void GetDateTime(void)

16: {

17: time_t now;

18:

19: printf(“Within GetDateTime().\n”);

20: time(&now);

21: printf(“Current date and time is: %s\n”,

22: asctime(localtime(&now)));

23: }

20 067231861x CH15 4.10.2000 11:03 AM Page 249

Working with Functions

249

I obtain the following output after I run the executable file, 15L02.exe, of the program in Listing 15.2:

15

Before the GetDateTime() function is called.

OUTPUT
Within GetDateTime().

Current date and time is: Sat Apr 05 11:50:10 1997

After the GetDateTime() function is called.

Other books

Don't Breathe a Word by Jennifer McMahon
Mr. August by Romes, Jan
Fever (Flu) by Wayne Simmons
A Rockstar's Valentine by K.t Fisher, Clarise Tan
Dangerous Sea by David Roberts
Wolf Protector by Milly Taiden
SEAL of Honor by Gary Williams
Spin Out by James Buchanan