Procedures and functions

void print_maximum(int a,int b)
{
....int max;
....max = (a>b)? a : b;
....printf("The max is %d\n", max);
}

print_maximum(this_one, that_one);

...

Declare the types of parameters before beginning the body.

Parameters have local scope, arguments are called by value.

No semicolon after the procedure heading.

int find_minimum(int A[], int n)
{
....int min=INFINITY;
....int k;
....for (k=0; k<n; ++k) {
........if (A[k]<min) min = A[k];
.......}
....return min;
}

optimum = find_minimum(myArray, mySize);

....

Don't specify the length of parameter arrays.

Arrays are passed by value, but an array is a pointer so changing A[3] within
the procedure will change an element of the argument array.

void get_min_and_max(int A[], int n, int *minp, int *maxp)
{
int small, large;
....int k;

....*minp=INFINITY;
....*maxp=NEG_INFINITY;
....if (n%2) {
........*minp = *maxp = A[--n];
........}

for (k=0; k<n; k+=2) {
....if (A[k]<A[k+1]) {
........small = A[k]; large = A[k+1];
........}
....else {
........small = A[k+1]; large = A[k];
........}
....if (small<*minp) *minp = small;
....if (large>*maxp) *maxp = large;
....}
}

get_min_and_max(ycoords, n, &ymin, &ymax);

....

 

Pass pointers to achieve the effect of Pascal var parameters, or Ada
out parameters.


char first_nonwhite(char *s)
{
char *cp=s;
....while (*cp==' ' || *cp=='\t' || *cp=='\n') ++cp;
....return *cp;
}


....c = first_nonwhite(" West Side Story ");
....c = first_nonwhite(buffer);

By default, every procedure (function) returns an int.
Precede the procedure heading with a type name to indicate return values of a
different type.

The return statement supplies the returned value.

struct person *
elect_president(candidate, n)
struct person candidate[];
int n;
{
int k;
....for (k=0; k<n; ++k) {
........if (candidate[k].votes > MAJORITY)
............return &(candidate[k]);
........}
}



..

.the_pres = elect_president(slate, num_parties);

.


Don't return a structure, return a pointer to a structure.