Добавил:
Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
C For Dummies 2nd Ed 2004.pdf
Скачиваний:
43
Добавлен:
17.08.2013
Размер:
8.34 Mб
Скачать

Chapter 20: Writing That First Function 255

Some functions return a value. That is, they produce something that your program can use, examine, compare, or whatever. The getchar() func­ tion returns a character typed at the keyboard, which is typically stored in a character variable; thus:

thus=getchar();

Some functions require parentheses stuff and return a value.

Other functions (such as playAlex()) neither require parentheses stuff nor return a value.

Functions are nothing new. Most C programs are full of them, such as printf(), getchar(), atoi(), and others. Unlike your own functions, these functions are part of the compiler’s library of functions. Even so, the functions you write work just like those others do.

Creating a function doesn’t really add a new word to the C language. How­ ever, you can use the function just like any other function in your pro­ grams; printf() and scanf(), for example.

A potentially redundant program in need of a function

I like to think of functions as removing the redundancy from programs. If any­ thing must be done more than once, shuffle it off into a function. That makes writing the program so much easier. It also breaks up the main() function in your source code (which can get tediously long).

The following sample program is BIGJERK1.C, a litany of sorts devoted to some­ one named Bill, who is a jerk:

#include <stdio.h>

int main()

{

printf(“He calls me on the phone with nothing say\n”); printf(“Not once, or twice, but three times a day!\n”); printf(“Bill is a jerk!\n”);

printf(“He insulted my wife, my cat, my mother\n”); printf(“He irritates and grates, like no other!\n”); printf(“Bill is a jerk!\n”);

printf(“He chuckles it off, his big belly a-heavin’\n”); printf(“But he won’t be laughing when I get even!\n”); printf(“Bill is a jerk!\n”);

return(0);

}

Type this program into your editor. Double-check all the parentheses and double quotes. They’re maddening. Maddening!

256 Part IV: C Level

Compile and run BIGJERK1.C. It displays the litany on the screen. Ho-hum.

Nothing big. Notice that one chunk of the program is repeated three times.

Smells like a good opportunity for a function.

Most of the redundancy a function removes is much more complex than a simple printf() statement. Ah, but this is a demo.

None of the Bills I personally know is a jerk. Feel free to change the name Bill into someone else’s name, if you feel the urge.

In the olden days (and I’m showing my age here), every byte in a program

was vital. A message such as Bill is a jerk repeated over and over meant that precious bytes of data were being wasted on a silly text string. Ancient programmers, such as myself, honed their skills by removing excess bytes from programs like this one. Shaving a program’s size from 4,096 bytes to 3,788 bytes was considered a worthy accomplishment. Of course, with today’s mega-/gigacomputers, saving space like that is con­ sidered trivial.

The noble jerk() function

It’s time to add your first new word to the C language — the jerk() function. Okay, jerk isn’t a C language word. It’s a function. But you use it in a program just as you would use any other C language word or function. The compiler doesn’t know the difference — as long as you set everything up properly.

Next, the new, improved “Bill is a jerk” program contains the noble jerk() function, right in there living next to the primary main() function. This pro­ gram is a major step in your programming skills — a moment to be savored. Pause to enjoy a beverage after typing it:

#include <stdio.h>

int main()

{

printf(“He calls me on the phone with nothing say\n”); printf(“Not once, or twice, but three times a day!\n”); jerk();

printf(“He insulted my wife, my cat, my mother\n”); printf(“He irritates and grates, like no other!\n”); jerk();

printf(“He chuckles it off, his big belly a-heavin’\n”); printf(“But he won’t be laughing when I get even!\n”); jerk();

return(0);

}

/* This is the jerk() function */

Chapter 20: Writing That First Function 257

jerk()

{

printf(“Bill is a jerk\n”);

}

Type the source code for BIGJERK2.C in your editor. Pay special attention to the formatting and such. Save the file to disk as BIGJERK2.C. Compile and run. The output from this program is the same as the first BIGJERK program.

Depending on your compiler, and how sensitive it has been set up for error reporting, you may see a slew of warning errors when you’re compil­ ing BIGJERK2.C: You may see a no prototype error; a Function should return a value error; a ‘jerk’ undefined error; or even a no return value error.

Despite the errors, the program should run. Those are mere “warning” errors — violations of C language protocol — not the more deadly, fatal errors, which means that the program is unable to work properly.

I show you how to cover — and cure — the errors in a few sections. Hold fast.

How the jerk() function works in BIGJERK2.C

A function works like a magic box. It produces something. In the case of the jerk() function in BIGJERK2.C, it produces a string of text displayed on the screen. Bill is a jerk — like that.

In the BIGJERK2.C program, the computer ambles along, executing C language instructions as normal, from top to bottom. Then, it encounters this line:

jerk();

That’s not a C language keyword, and it’s not a function known to the com­ piler. The computer looks around and finds a jerk() function defined in your source code. Contented, it jumps over to that spot and executes those state­ ments in that function. When it reaches the last curly brace in the function, the computer figures that it must be done, so it returns to where it was in the main program. This happens three times in BIGJERK2.C.

Figure 20-1 illustrates what’s happening in a graphic sense. Each time the com­ puter sees the jerk() function, it executes the commands in that function. This works just as though those statements were right there in the code (as shown in the figure) — which, incidentally, is exactly how the BIGJERK1.C program works.