Friday, October 16, 2009

Functions

Functions are the building blocks of C programs. Besides the standard C library functions, you can also use some
other functions made by you or by another programmer in your C program. The opening brace ({) signifies the start
of a function body, while (}), the closing brace, marks the end of the function body.
According to the ANSI standard, the declaration of a variable or function specifies the interpretation and attributes of
a set of identifiers. The definition, on the other hand, requires the C compiler to reserve storage for a variable or
function named by an identifier.
In fact, a variable declaration is a definition. But the same is not true for functions. A function declaration alludes to a
function that is defined elsewhere, and specifies what kind of value returned by the function. A function definition
defines what the function does, as well as the number and type of arguments passed to the function.
With the ANSI standard, the number and types of arguments passed to a function are allowed to be added into the
function declaration. The number and types of argument are called the function prototype.
The general form of a function declaration, including its prototype, is as follows:
data_type_specifier function_name(
data_type_specifier argument_name1,
data_type_specifier argument_name2,
data_type_specifier argument_name3,
.
.
.
data_type_specifier argument_nameN,
);
Here data_type_specifier determines the type of the return value made by the function or specifies the data types of
arguments, such as argument_name1, argument_name2, argument_name3, and argument_nameN, passed to the
function with the name of function_name.
The purpose of using a function prototype is to help the compiler to check whether the data types of arguments passed
to a function match what the function expects. The compiler issues an error message if the data types do not match.
The void data type is needed in the declaration of a function that takes no argument.
To declare a function that takes a variable number of arguments, you have to specify at least the first argument and
use the ellipsis (...) to represent the rest of the arguments passed to the function.
A function call is an expression that can be used as a single statement or within other expressions or statements.
It's more efficient to pass the address of an argument, instead of its copy, to a function so that the function can access
and manipulate the original value of the argument. Therefore, it's a good idea to pass the name of a pointer, which
points to an array, as an argument to a function, instead of the array elements themselves.
You can also call a function via a pointer that holds the address of the function.

No comments:

Post a Comment