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

262 Part IV: C Level

If your source code has more than one function, the order in which they’re listed is important; you cannot use a function inside your source code unless it has first been declared or prototyped. If you have multiple functions in your source code, order them so that if one function calls another, that second function is listed first. Otherwise, you’re again saddled with prototyping errors.

The Tao of Functions

The C language allows you to put as many functions as you want in your source code. There really is no limit, though most programmers like to keep their source-code text files to a manageable size.

What is “manageable size”? It depends.

The larger the source code file, the longer it takes to compile.

Often times, it pays to break off functions into their own, separate source code files. It not only aids in debugging, but also makes recompiling larger files easier.

This book’s companion volume, C All-in-One Desk Reference For Dummies

(Wiley), contains information on creating and managing multimodule source code files.

The function format

Here’s the format of a typical function:

type name(stuff)

The type tells the compiler whether the function returns a value. If the type is void, the function doesn’t return any value. (It merely functs.) Otherwise, the type describes which type of value the function returns: char, int, float, or any of the standard C language variable declarations.

The name is the function’s name. It must be a unique name, not any keywords or names of other C language library functions, such as printf() or atio(). (For more on names, see the next section.)

Parentheses after the function’s name are required, as they are on all C language functions. The stuff inside the parentheses, if needed, defines whatever value (or values) are sent off to the function for evaluation, manipulation, or mutila­ tion. I cover this subject in Chapter 22. If there’s no stuff, the parentheses can be left empty or the word void can be used.

Chapter 20: Writing That First Function 263

The statements belonging to the function require curly braces to hug them close. Those statements are the instructions that carry out what the function is supposed to do. Therefore, the full format for the function is shown here:

type name(stuff)

{

statement(s);

/* more statements */

}

The function must be prototyped before it can be used. You do that by either listing the full function earlier than it’s first used in your source code or restat­ ing the function’s declaration at the start of your source code. For example:

type name(stuff);

This line, with a semicolon, is required in order to prototype the function used later on in the program. It’s just a copy-and-paste job, but the semicolon is required for the prototype. (If you forget, your compiler may ever so gently remind you with a barrage of error messages.)

Call it defining a function. Call it declaring a function. Call it doing a func­ tion. (The official term is defining a function.)

Naming rules for functions are covered in the next section.

Your C language library reference lists functions by using the preceding format. For example:

int atoi(const char *s);

This format explains the requirements and product of the atoi() func­ tion. Its type is an int, and its stuff is a character string, which is how you translate const char *s into English. (Also noted in the format is that the #include <stdlib.h> thing is required at the beginning of your source code when you use the atoi() function.)

How to name your functions

Functions are like your children, so, for heaven’s sake, don’t give them a dorky name! You’re free to give your functions just about any name, but keep in mind these notes:

Functions are named by using letters of the alphabet and numbers. Almost all compilers insist that your functions begin with a letter. Check your compiler’s documentation to see whether this issue is something your compiler is fussy about.

264 Part IV: C Level

Don’t use spaces in your function names. Instead, use underlines. For example, this isn’t a function name:

get the time()

But this is:

get_the_time()

You can use upperor lowercase when you’re naming your functions. A common tactic is to capitalize key letters in the function’s name:

getTheTime()

Most compilers are case sensitive, so if you use mixed case, be sure to remember how you type it. For example, if the function is named getTheTime and you type GetTheTime, you may get a linker error (the function was not found).

Keep your function names short and descriptive. A function named f() is permissible yet ambiguous — it’s like saying “Nothing” when someone asks you what you’re thinking.

Some compilers may forbid you to begin a function name with an under­ line. It sounds bizarre, I know, but the following may be verboten:

_whatever()

Avoid naming your functions the same as other C language functions or keywords. Be unique!

The function name main() is reserved for your program’s first function.

Chapter 21

Contending with Variables in Functions

In This Chapter

Naming variables within functions

Understanding local variables

Sharing one variable throughout a program

Using global variables

Each function you create can use its own, private set of variables. It’s a must. Just like the main() function, other functions require integer or character

variables that help the function do its job. A few quirks are involved with this arrangement, of course — a few head-scratchers that must be properly mulled over so that you can understand the enter function/variable gestalt.

This chapter introduces you to the strange concept of variables inside func­ tions. They’re different. They’re unique. Please avoid the desire to kill them.

Bombs Away with the

BOMBER Program!

The dropBomb() function in the BOMBER.C program uses its own, private vari­ able x in a for loop to simulate a bomb dropping. It could be an exciting ele­ ment of a computer game you may yearn to write, though you probably want to use sophisticated graphics rather than the sloppy console screen used here:

#include <stdio.h>

void dropBomb(void);

/* prototype */

int main()

266 Part IV: C Level

{

printf(“Press Enter to drop the bomb:”); getchar();

dropBomb();

printf(“Yikes!\n”);

return(0);

}

void dropBomb()

{

int x;

for(x=20;x>1;x--)

{

puts(“ *”);

}

puts(“ BOOM!”);

}

Type the source code as listed here. In the puts() function in Line 20 are 10 spaces before the asterisk.) In Line 22 are 8 spaces before BOOM!.

Save the file to disk as BOMBER.C. Compile and run.

Press Enter to drop the bomb:

*

*

*

And so on. . . .

*

*

BOOM!

Yikes!

Yeah, it happens a little too fast to build up the nerve-tingling anticipation of a true video game, but the point here is not dropping bombs; rather, the vari­ able x is used in the dropBomb() function. It works just fine. Nothing quirky. Nothing new. That’s how variables are used in functions.

See how the dropBomb() function declares the variable x:

int x;

It works just like it does in the main() function: Declare the variables right up front. Refer to Chapter 8 for more information about declaring variables.

The dropBomb() function is a void because it doesn’t return any values. It has nothing to do with any values used inside the function.