Introduction to functions in C
Call by Value and call by
Reference parameter technique
Bigger pointer example
The keyword "static"
defines that the function will only be available to callers in the file
where it is declared. If a function needs to be called from another file,
the function cannot be static and will require a prototype -- see prototypes
below. The static form
is convenient for utility functions which will only be used in the file
where they are
declared. Next , the "int" in the function above is the type of its return
value. Next comes name of the function and its list of parameters. When
referring to a function by
name in documentation or other prose, it's a convention to keep the
parenthesis () suffix,
so in this case I refer to the function as "Twice()". The parameters are
listed with their types and names, just like variables.
Inside the function, the parameter num and the local variable result are
"local" to the function -- they get their own memory and exist only so long
as the function is executing. This independence of "local" memory is a
standard feature of most languages (See CSLibrary/102 for the detailed
discussion of local memory).
The "caller" code which calls Twice() looks like...
int num = 13;
int a = 1;
int b = 2;
a = Twice(a); // call Twice() passing the value of a
b = Twice(b + num); // call Twice() passing the value b+num
// a == 2
// b == 30
// num == 13 (this num is totally independent of the "num" local to Twice()
Things to notice...
(vocabulary) The expression passed to a function by its caller is called the
"actual parameter" -- such as "a" and "b + num" above. The parameter storage
local to the function is called the "formal parameter" such as the "num" in
"static int Twice(int num)".
Parameters are passed "by value" that means there is a single copying
assignment operation (=) from each actual parameter to set each formal
parameter. The actual parameter is evaluated in the caller's context, and
then the value is copied into the
function's formal parameter just before the function begins executing. The
alternative parameter mechanism is "by reference" which C does not implement
which the programmer can implement manually when needed (see below). When a
parameter is a struct, it is copied.
The variables local to Twice(), num and result, only exist temporarily while
Twice() is executing. This is the standard definition for "local" storage
The return at the end of Twice() computes the return value and exits the
function. Execution resumes with the caller. There can be multiple return
statements within a function, but it's good style to at least have one at
the end if a return value needs to be specified. Forgetting to account of a
return somewhere in the middle of a function
is a traditional source of bugs.
Want To Know more with
Contact for more learning: webmaster@freehost7com