Sams Teach Yourself C in 21 Days

(singke) #1
Packaging Code in Functions 109

5


they are declared. You can declare any of C’s variable types in a function. Here is an
example of four local variables being declared within a function:
int func1(int y)
{
int a, b = 10;
float rate;
double cost = 12.55;
/* function code goes here... */
}
The preceding declarations create the local variables a,b,rate, andcost, which can be
used by the code in the function. Note that the function parameters are considered to be
variable declarations, so the variables, if any, in the function’s parameter list also are
available.
When you declare and use a variable in a function, it is totally separate and distinct from
any other variables that are declared elsewhere in the program. This is true even if the
variables have the same name. Listing 5.3 demonstrates this independence.

LISTING5.3 var.c. A demonstration of local variables
1: /* Demonstrates local variables. */
2:
3: #include <stdio.h>
4:
5: int x = 1, y = 2;
6:
7: void demo(void);
8:
9: int main( void )
10: {
11: printf(“\nBefore calling demo(), x = %d and y = %d.”, x, y);
12: demo();
13: printf(“\nAfter calling demo(), x = %d and y = %d\n.”, x, y);
14:
15: return 0;
16: }
17:
18: void demo(void)
19: {
20: /* Declare and initialize two local variables. */
21:
22: int x = 88, y = 99;
23:
24: /* Display their values. */
25:
26: printf(“\nWithin demo(), x = %d and y = %d.”, x, y);
27: }

09 448201x-CH05 8/13/02 11:15 AM Page 109

Free download pdf