Functions

printf, scanf, isalpha, ... are all functions.

Functions must be called to be executed.

“Experience has shown that the best way to develop and maintain a large program is to construct it from smaller pieces or modules, each of which is more manageable than the original program.”

Factoring your code into functions helps...

You know you need to put code in a new function when...

Defining Functions

Function definition should appear before it is used.

int foo(char c, int i) {
	return i;
 }

A function return nothing has return type void, and does not need a return statement.

Use empty parameter list () or (void) if the function does not have parameters.

Declaring Functions

We can "declare" a function before the function that calls it, then fully define it later (after main()), after calling function's definition.

flaot func1 (int x, float y); // declaration

Communication Between Functions

Functions communicate with function parameters and/or function return values.

External (global) variables are another option; though use of these is discouraged.

Parameter passing

Argument values in C are passed by values.

As soon you return from the function, all the local things will go away, such as the parameters. This means, you cannot return local arrays.

Passing Arrays

Arrays and C Strings are not passed by value. Instead, passing array amounts to passing a pointer to its first element because copying would be excessive.

Now, the callee can modify the array.
Example:

// multiply each array element by factor, modifying the array.
void scale_array (float arr[], int len, float factor) {
	for (int i = 0; i < len; i++) {
		arr[i] *= factor;
	}
}

When an array parameter should not be modified by the function, add const before the type. Compiler gives an error if you try to modify a const variable because it is read-only.

Returning an Array

The return type is the array's base type with * added (a pointer).

For now, we can pass in an empty array to fill. Instead of returning a local array, caller should pass in "destination" array to modify.

Command-Line Arguments

When you tyep mkdir cs220 you're running a program called mkdir and passing it a single command-line argument, cs220.

C programs can take arguments similar to this way, but you have to declare your main function in a special way:

int main(int argc, char* argv[]) {
    ...
}

Math Functions

#include math.h and compile with -lm option (includes the math library when linking to the gcc command to get access to:

x and y arguments have a type double. Passing int is also OK.