PAGEFLOP
FORWARD
SELECTOR
SELAGAIN
WRONGSEL
YOUR SELECTION IS NOT IN THE 0 - #SELIMIT RANGE Please try again
NEXT
$V1$
$V1$
AANVANG
Copyright CourseWare Technologies Inc., 1985-88
Lesson - 4
C PROGRAMS AND FUNCTIONS
P1
Programs & Functions|Topics to Learn|4-0|13,40
# Topic
--- -------
1 - Functions
2 - The return Statement
3 - Function Arguments
4 - First Review
5 - Storage Class Specifiers
6 - The Scope of Variables
7 - Character Arrays
8 - Static and Register Variables
9 - Program Development Cycle
10 - Second Review
0 - Return to the Main Menu
P2
Programs & Functions|Functions|4-1.1|12,54
A function is the basic module or building
block of a program, capable of performing arithmetic,
control, storage, input or output.
A C program is made up of one or more functions.
These functions may reside in one or more source files.
Functions may be compiled separately and then
loaded together with other previously compiled functions
from various libraries.
P3
Programs & Functions|Functions|4-1.2| 18 , 55
A function must be defined or made available to
the program that will use it.
Syntax for Defining a Function
_______________________________________________________
| |
| [type_specifier] function_name([argument_list]) |
|
| [argument declarations;] |
| { |
| [internal_var.declarations;] |
| |
| statement(s); |
| } |
| |
| Where brackets [] denote optional elements and |
| argument declarations must follow the argument_list |
| |
-------------------------------------------------------
P4
Programs & Functions|The return Statement|4-2.1|17,57
The return statement is an optional mechanism
for returning a value and the program control from the
called function to its caller.
Syntax: return [expression];
Notes:
* A function need not have a return statement.
* The return statement need not return any value.
* If the return statement returns no value and
this occurs before the closing brace, the return
statement is equivalent to no return statement
at all.
P5
Programs & Functions|The return Statement|4-2.2|14,54
In this example, return only returns program control.
#include <stdio.h>
#define BELL 7
#define EOF (-1)
alarm_check()
{
int c;
while ((c = getchar()) != EOF)
if (c == BELL) { /* check if BELL character */
printf("ALARM!!!!!\n");
return;
}
}
P6
Programs & Functions|The return Statement|4-2.3|8,54
In the following example the return statement is
a mathematical expression. The return expression
inside will be evaluated before the value is returned.
n represents the number of items, stamp_val
represents the cost of one stamp, and region
represents the geographical regions. Note that the
ternary operator is used to determine the appropriate
tax. This is a typical use for the ternary operator.
P7
Programs & Functions|The return Statement|4-2.4|13,56
/* calculate the cost of stamps in cents including tax,
and return the cost value */
stamp_cost(n, stamp_val, region)
int n, region;
int stamp_val; /* cost per stamp in cents */
{
float tax1 = 1.065, tax2 = 1.04; /* local taxes */
float tax; /* calculated tax */
tax = (region == 1) ? tax1 : tax2;
return ( n * stamp_val * tax);
}
P8
Programs & Functions|The return Statement|4-2.5|14,59
In this example return returns a value to the calling
function. The function force_f() is explicitly declared
as type float. The compiler will check to make sure that
the type of the returned variable is the same as the type
of the function float.
float force_f(m,a) /* calculate force */
float m,a;
{
float force;
force = m * a;
return (force);
}
P9
Programs & Functions|The return Statement|4-2.6|4,54
If the function returns data of a type other
than int, the function type must be specified in both
the function header itself and inside the body of the
calling function.
P10
Programs & Functions|The return Statement|4-2.7|16,54
The function below is declared with no type, therefore,
if there is a return statement, it should return a
variable of type int by default.
/* define a function, force_f() which returns a
non-integer inside the body of the calling function funcx() */
funcx()
{
float mass, accel;
float cur_force, force_f();
:
cur_force = force_f(mass,accel);
}
P11
Programs & Functions|Function Arguments|4-3.1|11,54
An argument list is used for passing data
(variables) from the calling to the called functions.
Variables in the argument list are enclosed
in parentheses following the function name.
The type of argument is declared after the
argument list, but prior to the opening brace for
the function.
P12
Programs & Functions|Function Arguments|4-3.2|14,54
The following function has three arguments passed to
it, len, height, and width, all of type int. Note
that the arguments are declared prior to the opening
brace for the function.
/* an argument list is followed by argument
declarations */
volume(len, height, width)
int len, height, width;
{
...
...
}
P13
Programs & Functions|Function Arguments|4-3.3|14,54
The following function, warning(), has no arguments
passed to it, and therefore has no arguments declared
prior to the opening brace. Functions with no arguments
normally perform some defined, unchanging operations,
or use global variables for internal calculations.
/* The function warning() uses no arguments at all */
warning()
{
...
...
}
P14
Programs & Functions|Function Arguments|4-3.4|10,60
Variables used in a function that don't appear in
the argument list must be declared after the opening brace.
The following function, num_of_orders(), calculates the
number of orders for various merchandise. The array orders
holds the quantities for each order. The delimiting entry
is 0, i.e., no orders. This function will return the
number of orders received or a -1 (ERROR status) if 0 is
not encountered in the array, i.e., if the array was
constructed incorrectly.
P15
Programs & Functions|Function Arguments|4-3.5|14,54
/* calculate number of orders, order_delimiter=0.
If number of orders > max, then an error in
the order array exists. */
#define STOP_VALUE 0
num_of_orders(order,max)
int order[50], max;
{
int i; /* internal variable */
for (i = 0; i < max && order[i] !=
STOP_VALUE; i++);
return ((order[i] == STOP_VALUE) ? i:-1);
}
P16
Programs & Functions|Function Arguments|4-3.6|3,54
It is the responsibility of the programmer to make
sure that the argument number and the argument type
match.
P17
Programs & Functions|Storage Class Specifiers|4-5.1|11,56
There are 4 different storage class specifiers in C
* extern specifies scope
* auto specifies scope
* static specifies the length of
existence and the scope
* register specifies usage
P18
Programs & Functions|The Scope of Variables|4-6.1|16,54
A C program consists of a set of external objects
which are either functions or variables.
External variables are declared outside a function
and are potentially available to all the functions in
the same program.
External variables retain their values throughout
the lifetime of the program.
To reference an external variable inside another
function in a different file, the external variable
must be defined with a prefix extern.
P19
Programs & Functions|The Scope of Variables|4-6.2|17,64
The following two files illustrate the scope of variable
stamp_num. stamp_num inside file_1 hides the external variable
step_num. proc2() in file_2 refers to the external declaration
of stamp_num in file_1.
file_1 file_2
int stamp_num;
main() proc2()
{ {
extern int stamp_num;
:
} }
proc1()
{
int stamp_num;
}
P20
Programs & Functions|The Scope of Variables|4-6.3|4,54
Note: if there is an internal variable with the
same name as the external variable, then the function
in which the internal variable is declared, sees (knows)
only about the internal (local) variable.
P21
Programs & Functions|The Scope of Variables|4-6.4|14,54
An automatic variable, the default storage
class for variables, is known only to the function
in which it is declared.
The prefix auto is optional.
By default, a undeclared or an auto variable
is an int.
The value of an automatic or local variable is
lost on leaving the function.
P22
Programs & Functions|Character Arrays|4-7.1|17,54
An array is a homogeneous data structure that
groups together variables of identical data types
under a common name.
A character array is an array that may hold
several single characters.
An Array index in C always starts at zero.
Every character array should be terminated with a
null character: '\0'.
For example, c_class is stored as |c|_|c|l|a|s|s|\0|
P23
Programs & Functions|Character Arrays|4-7.2|13,61
The following rather involved example reflects a realistic
tasks that you may face. The program will read text from
the standard input or a file and fold any line that is
longer than a certain legal length (like 60 characters).
Three functions are used in the process:
main() - the controlling function;
read_line() - reads a line of text;
trim_line() - folds the line to the specified
legal length
The results are verified at the standard output. Note
that the buffer buffer_line is a global object.
P24
Programs & Functions|Character Arrays|4-7.3|9,58
The most involved function is trim_line() which operates
on the following principle: First it starts at the end
of the buffer and looks for a blank or a tab so it won't
split a word. If none is found, the length is set to
the legal length. Then LEGAL_LEN number of characters
are copied into the variable line and everything else in
buffer_line is moved forward. This process continues until
the number of characters in buffer_line is less than
LEGAL_LEN, when folding is no longer necessary.
P25
Programs & Functions|Character Arrays|4-7.4|17,54
PROBLEM: Read a set of lines from the terminal and fold any
line longer than the specified legal length.
/* the outline for this program in English */
WHILE ( there is another line )
IF (line NOT longer than 60 )
print current line
ELSE
WHILE (line longer than legal length)
fold the line
print current legal length line
END WHILE
print current legal length line
print the remainder of the line
ENDIF
END WHILE
P26
Programs & Functions|Character Arrays|4-7.5|18,56
/* Example ----------------------------------- Page 1 */
#define MAXLINE 500 /* maximum line length */
#define LEGAL_LEN 50 /* legal line length */
char buffer_line[MAXLINE+1]; /* line buffer */
main() /* fold lines longer than LEGAL_LEN */
{ int len; /* line length variables */
extern char buffer_line[];
char line[LEGAL_LEN + 1]; /* legal line buffer */
while(( len = read_line (MAXLINE)) > 0)
if (len <= LEGAL_LEN)
printf("%s\n",buffer_line);
else {
while (trim_line(line, LEGAL_LEN) > LEGAL_LEN)
printf("%s\n", line); /* print current line */
printf("%s\n", line);
printf("%s\n", buffer_line);
}
}
P27
Programs & Functions|Character Arrays|4-7.6|17,56
/* Example ----------------------------------- Page 2 */
#include <stdio.h>
read_line(max) /* read current line */
int max; /* maximum buffer line length*/
{
extern char buffer_line[];
int i = 0 , j, c;
printf("Enter New Line\n");
while ( (c = getchar()) != '\n' &&
c != EOF && i < max )
buffer_line[i++] = c;
buffer_line[i] = '\0'; /* NULL to end of string */
return (i); /* return string length */
}
P28
Programs & Functions|Character Arrays|4-7.7|15,54
/* Example ----------------------------------- Page 3 */
trim_line (line, max) /* get next legal length line */
char line[];
int max;
{
int i, j, c;
extern char buffer_line[];
/* find 1st blank or tab going back from max */
i = max -1;
while ((c = buffer_line[i]) != ' ' &&
c != '\t' && i > 0)
i--;
P29
Programs & Functions|Character Arrays|4-7.8|15,54
/* Example ----------------------------------- Page 4 */
/* COPY LEGAL SIZE LINE */
if (i = 0) /* word > max => max */
i = max -1;
for (j = 0; j <= i-1; j++)
line[j] = buffer_line[j];
line[j] = '\0'; /* end of string */
/* THROW AWAY ANY LEADING BLANKS OR TABS */
while((c = buffer_line[++i])== ' ' |c == '\t');
/* UPDATE CURRENT BUFFER LINE */
for (j=0; buffer_line[j] = buffer_line[i]; j++, ++i);
return (strlen(buffer_line));
}
P30
Programs & Functions|Character Arrays|4-7.9|11,49
There are three source files in the preceding
program which contain the functions:
main(), read_line() and trim_line()
There is 1 external variable: buffer_line
The declaration of the external variable
buffer_line in main() is redundant.
P31
Programs & Functions|Static Variables|4-8.1|8,54
A variable declared with the prefix static remains
alive, that is, retains valid value throughout the
lifetime of the program.
/* typical STATIC variable declarations */
static int student_count;
static long buff_index;
P32
Programs & Functions|Static Variables|4-8.2|11,54
The scope of an internal static variable is
the same as the scope of an automatic variable.
The scope of an external static variable is
all the functions in the file where the static
variable is declared.
The scope of a static function is the same
as that of an external static variable.
P33
Programs & Functions|Static Variables|4-8.3|14,56
The following three screens present a program that is
made up of functions contained in three files. The
variable of interest to us is x. In the first file,
the variable outside the main() is the global or the
external variable int x. It is declared inside the
function funct_1() and remains alive during the
lifetime of the entire program.
The static variable int x declared outside the
function funct_3() in the second file is global to
both funct_2() and funct_3() and remains alive
throughout the lifetime of the program. NOTE: the
scope of the external static variable is only the
functions in the same file!
P34
Programs & Functions|Static Variables|4-8.4|16,48
/* Using static variables in 3 different files;
refer to the following screens also. */
FILE 1
--------
int x;
main()
{
:
:
}
funct_1()
{
static int x;
}
P35
Programs & Functions|Static Variables|4-8.5|13,54
FILE 2
--------
static int x; /* scope limited to file 2 */
funct_2()
{
func_3();
: }
funct_3()
{
:
x = x + 2; /* refers to static x in funct_2() */
}
P36
Programs & Functions|Static Variables|4-8.6|6,50
FILE 3
--------
funct_4()
{ /* file_3 */
extern int x; /* refers to x in file_1 */
}
P37
Programs & Functions|Register Variables|4-8.7|12,56
A variable declared with the prefix register tells
the compiler that the user desires a cpu register to be
used for storage and manipulation of the variable.
The type of register variables allowed varies from
machine to machine.
/* typical register variables declarations */
register int tab_index;
register float div_variable;
P38
Programs & Functions|Program Development Cycle|4-9.1|10,54
To illustrate the program development cycle,
recall that the program fold_line was made up of 3
source files: fold_line.c, read_line.c, and
trim_line.c
You can compile the program to produce object
files only with:
cc -c fold_line.c read_line.c trim_line.c
P39
Programs & Functions|Program Development Cycle|4-9.2|14,62
You can compile the program to produce an executable image
from object files with:
cc -o fold_line fold_line.o read_line.o trim_line.o
Or, you can do this directly with:
cc -o fold_line fold_line.c read_line.c trim_line.c
To recompile read_line.c and link in the object files for
others, use:
cc -o fold_line fold_line.o read_line.c trim_line.o