This lesson will show you how to:
- write programs using functions
- write programs using local and global variables
Q: What do a blonde and an instant lottery ticket have
in common?
A: All you have to do is scratch the box to win.
A function in C can perform a particular task, and supports
the concept of modular programming design techniques.
We have already been exposed to functions. The main body
of a C program, identified by the keyword main,
and enclosed by the left and right braces is a function.
It is called by the operating system when the program
is loaded, and when terminated, returns to the operating
system.
Functions have a basic structure. Their format is:
return_ data_type function name (arguments, arguments)
data _type _declarations of
arguments;
{
function
body
}
It is worth noting that a return data type is assumed
to be of type int unless otherwise specified,
thus programs we have seen so far imply that main()
returns an integer to the operating system. ANSI C varies
slightly in the way that functions are declared. Its format
is:
return_data_type function name (data type variable
name, data type variable name,….)
{
function body
}
This permits type checking by utilizing function prototypes
to inform the compiler of the type and number of parameters
a function accepts. When calling a function, this information
is used to perform the type and parameter checking.
ANSI C also requires that the return_ data_type for a
function which does not return data must my of type void.
The default return_ data_type is assumed to be an integer
unless otherwise specified, but must match that which
the function declaration specifies. A simple function
is:
int print_message ()
{
printf(“This is a module
called print_message.\n”);
}
Note the function name is print_message. No arguments
are accepted by the function, this is indicated by the
keyword void in accepted parameter section of function
declaration. The return_data_type is void, this data is
not returned by the function. An ANSI C function prototype
for print_message() is:
int print_message ();
Function prototypes are listed at the beginning of the
source file. Often, they might be placed in a users .h
(header) file.
Functions
Now lets incorporate this function into a program.
/* Program illustrating a simple function call */
#include <stdio.h>
void print_message (void); /*
ANSI C function prototype */
void print_message (void) /*
the function code */
{
printf(“This is a module
called print_message.\n”);
}
int main(void)
{
print_message();
return 0;
}
Sample program output
This is a module called print_message.
To call a function, it is only necessary to write its
name. The code associated with the function is executed
at this point in the program. When the function terminates,
execution begins with the statement which follows the
function name.
In the above program, execution begins at main().
The only statement inside main the main body of the program
is a call to the code of function print_message().
This code is executed, and when finished returns control
back to main().
As there is no further example, the function accepts
a single data variable, but does not return any information.
/* Program to calculate a specific factorial number */
#iinclude <stdio.h>
void calc_factorial (int); // ANSI function prototype
void calc_factorial (int i)
{
int I, factorial_number = 1;
for (i=1; I <=n; ++i)
factorial_number
*= I;
printf(“The factorial
of %d is %d\n”, n, factorial_number);
}
int main(void)
{
int number = 0;
printf(“Enter a number\n”);
scanf(“%d”, &number);
calc_factorial (number);
return 0;
}
Sample program output
Enter a number
3
The factorial of 3 is 6
Lets look at the function calc_factorial().
The declaration of the function
void calc_factorial (int n)
Indicates there is no return data type and a single integer
is accepted, known inside the body of the function as
n. Next comes the declaration of the local variables.
int i, factorial_ number = 0;
It is more correct in C to use:
auto int i, factorial_number
= 0;
As the keyword auto designates to the compiler
that the variable is local. The program works by accepting
a variable from the keyboard which is then passed to the
function. In other words, the variable number inside the
main body is then copied to the variable n in the function,
which then calculates the correct answer.
Returning function results
This is done by the use of the keyword return, followed
by a data_variable or constant value, the data type os
which must match that of the declared return_data_type
for the function.
float add_numbers (float n1, float n2)
{
return n1 + n2; //
legal
return 6; //
illegal, not the same type
return 6.0; //
legal
}
It is possible for a function to have multiple return
statements.
int validate_input (char command)
{
switch (command)
{
case
‘+’ :
case
‘-‘ : return 1;
case
‘*’ :
case
‘/’ : return 2;
default
: return 0;
}
}
Here is another example
/* Simple multiply program using argument passing */
#include <stdio.h>
int calc_result (int, int) // ANSI function prototype
{
auto int result;
result = numb1 * numb2;
return result;
}
int main(void)
{
int digit1 = 10, digit2 = 30,
answer = 0;
answer = calc_result(digit1,
digit2);
printf(“%d multiplied
by %d is %d\n”, digit1, digit2, answer);
return 0;
}
Sample program output
10 multiplied by 30 is 300
NOTE that the value which is returned from the function
(ie result) must be declared in the function.
NOTE: The formal declaration of the function name is preceded
by the data type which is returned,
int calc_result (numb1, numb2)
Local and global variables
Local:
These variables only exist inside
the specific function that creates them. They are unknown
to other functions and to the main program. As such, they
are normally implemented using a stack. Local variables
cease to exist once the function that created them is
completed. They are recreated each time a function is
executed or called.
Global:
These variables can be accessed
(ie known) by any function comprising the program. They
are implemented by associating memory locations with variable
names. They do not get recreated if the function is recalled.
To declare a global variable, declare it outside of all
the functions. There is no general rule for where outside
the functions these should be declared, but declaring
them on top of the code is normally recommended for reasons
of scope, as explained below. If a variable of the same
name is declared both within a function and outside of
it, the function will use the variable that was declared
within it and ignore the global one.
I recommend to use as few global variables as possible.
Defining global variables:
/* Demonstrating global variables */
#include <stdio.h>
int add_numbers( void); // ANSI function prototype
/* These are global variables and can be accessed by
functions from this point on */
int value1, value2, value3;
int add_numbers (void)
{
auto int result;
result = value1 + value2 + value3;
return result;
}
int main(void)
{
auto int result;
value1 = 10;
value2 = 20;
value3 = 30;
result = add_numbers();
printf(“The sum of %d
+ %d + %d is %d\n”, value1, / value2,
value3, final_result);
return 0;
}
Sample program output
The scope of a global variable can be restricted by carefully
placing the declaration. They are visible from the declaration
until the end of the current source file.
#include <stdio.h>
int no_access (void); // ANSI
function prototype
int all_access(void);
static int n2; // n2 is known from this point onwards
int no_access (void)
{
n1 = 10; //
illegal, n1 not yet known
n2 = 5; //
valid
}
int all_access(void)
{
n1 = 10; //
valid
n2 = 3;
//
valid
}
back to top exercises lesson10 lesson
12