The datatype of a function
There are two distinct categories of functions in C:
- functions whose role is to just perform a task,
and to then return control
to the statement (pedantically, the expression)
that called it.
Such functions often have side-effects,
such as performing some output,
or modifying a global variable so that other statements may access that
modified value.
These functions don't return a specific value to the caller,
are termed void functions,
and we casually say that they "return void".
- functions whose role is to calculate a value,
and to return that value for use in the expressions that called them.
The single value returned will have a type,
such as
int,
char,
bool, or
float.
These functions may also have side-effects.
#include <stdio.h>
#include <stdlib.h>
void output(char ch, int n)
{
for(int i=1 ; i<=n ; i=i+1) {
printf("%c", ch);
}
}
int main(int argc, char *argv[])
{
output(' ', 19);
output('*', 1);
output('\n', 1);
return 0;
}
|
|
#include <stdio.h>
#include <stdlib.h>
extern double sqrt(double x);
float square(float x)
{
return x * x;
}
int main(int argc, char *argv[])
{
if(argc > 2) {
float a, b, sum;
a = atof(argv[1]);
b = atof(argv[2]);
sum = square(a) + square(b);
printf("hypotenuse = %f\n",
sqrt(sum) );
}
return 0;
}
|
|
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
float square(float x)
{
return x * x;
}
int main(int argc, char *argv[])
{
if(argc > 2) {
float a, b, sum;
a = atof(argv[1]);
b = atof(argv[2]);
sum = square(a) + square(b);
printf("hypotenuse = %f\n",
sqrt(sum) );
}
return 0;
}
|
|
In the 2nd example we have provided
a function prototype to declare sqrt()
as an external function -
it is defined externally to this source file.
In the 3rd example,
we're being more correct,
by #includ-ing the <math.h> header file -
instructing the C compiler find the correct prototype for sqrt()
on this system.
In the 2nd and 3rd cases we must
compile the examples with:
cc [EXTRAOPTIONS] -o program program.c -lm
to instruct the linker to search the math library for any missing code
(we require the sqrt() function).
CITS2002 Systems Programming, Lecture 4, p5, 31st July 2024.
|